Skip to content

Instantly share code, notes, and snippets.

@demircimurat
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save demircimurat/0f4cbc23b7a168f16c84 to your computer and use it in GitHub Desktop.
Save demircimurat/0f4cbc23b7a168f16c84 to your computer and use it in GitHub Desktop.
Object or Array to Dynamic in C#
/*
* based on Jorge Fioranelli's code..
* http://blog.jorgef.net/2011/06/converting-any-object-to-dynamic.html
*/
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;
}
if (value.GetType().IsArray) {
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment