-
-
Save orhanveli/fbc88bf92bc4c2f00137 to your computer and use it in GitHub Desktop.
Object or Array to Dynamic in C#
This file contains 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 class Extensions | |
{ | |
public static dynamic ToDynamic(this object value) | |
{ | |
if (value.IsListOrArray ()) { | |
var list = new List<ExpandoObject> (); | |
IEnumerable enumerable = value as IEnumerable; | |
foreach (object o in enumerable) { | |
list.Add (o.ToDynamic ()); | |
} | |
return (dynamic) list; | |
} | |
IDictionary<string, object> expando = new ExpandoObject (); | |
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType())) { | |
expando.Add (property.Name, property.GetValue (value)); | |
} | |
return (dynamic) expando; | |
} | |
public static bool IsListOrArray(this object value) | |
{ | |
if(value is IList && value.GetType().IsGenericType) { | |
return true; | |
} | |
var valueType = value.GetType (); | |
if (valueType.IsArray) { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment