Created
March 19, 2020 13:39
-
-
Save hancheester/e99be6c4429fbc8335b5bd614523219b to your computer and use it in GitHub Desktop.
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
/* | |
To parse value from a dynamic object. | |
*/ | |
public T Parse<T>(dynamic value, string name) | |
{ | |
if (CheckProperty(value, name)) | |
{ | |
var parts = name.Split("."); | |
if (parts.Length == 1) | |
return value.GetType().GetProperty(name).GetValue(value, null); | |
var obj = value; | |
foreach (var part in parts) | |
{ | |
if (obj == null) return default; | |
var property = obj.GetType().GetProperty(part); | |
if (obj == null) return default; | |
obj = property.GetValue(obj, null); | |
} | |
return obj; | |
} | |
return default; | |
} | |
public bool IsPropertyExist(dynamic value, string name) | |
{ | |
if (value is ExpandoObject) | |
return ((IDictionary<string, object>)value).ContainsKey(name); | |
return value.GetType().GetProperty(name) != null; | |
} | |
public bool CheckProperty(dynamic value, string name) | |
{ | |
var groups = name.Split("."); | |
foreach (var group in groups) | |
{ | |
if (IsPropertyExist(value, group) == false) | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment