Last active
August 2, 2022 07:43
-
-
Save enisn/aa07da19858c303454febf320b4f1890 to your computer and use it in GitHub Desktop.
Challenge #2 - Solution - GetPropValue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static object GetPropValue(this object obj, string name) | |
{ | |
if (obj == null) | |
{ | |
return null; | |
} | |
foreach (string part in name.Split('.')) | |
{ | |
if (obj.IsNonStringEnumerable()) | |
{ | |
var toEnumerable = (IEnumerable)obj; | |
var iterator = toEnumerable.GetEnumerator(); | |
if (!iterator.MoveNext()) | |
{ | |
return null; | |
} | |
obj = iterator.Current; | |
} | |
Type type = obj.GetType(); | |
PropertyInfo info = type.GetProperty(part); | |
if (info == null) { return null; } | |
obj = info.GetValue(obj, null); | |
} | |
return obj; | |
} | |
private static bool IsNonStringEnumerable(this object instance) | |
{ | |
return instance != null && instance.GetType().IsNonStringEnumerable(); | |
} | |
private static bool IsNonStringEnumerable(this Type type) | |
{ | |
if (type == null || type == typeof(string)) | |
return false; | |
return typeof(IEnumerable).IsAssignableFrom(type); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment