Skip to content

Instantly share code, notes, and snippets.

@orhanveli
Forked from demircimurat/gist:0f4cbc23b7a168f16c84
Last active October 17, 2017 19:15
Show Gist options
  • Save orhanveli/fbc88bf92bc4c2f00137 to your computer and use it in GitHub Desktop.
Save orhanveli/fbc88bf92bc4c2f00137 to your computer and use it in GitHub Desktop.
Object or Array to Dynamic in C#
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