Skip to content

Instantly share code, notes, and snippets.

@jchannon
Forked from orhanveli/ToDynamic.cs
Created October 17, 2017 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchannon/3579f43849ca497caeb00730a6106616 to your computer and use it in GitHub Desktop.
Save jchannon/3579f43849ca497caeb00730a6106616 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