I think ASP.NET MVC didn't exit at the time this question was made. It does convert anonymous objects to dictionaries internally.
Just take a look at the HtmlHelper
class, for example. The method that translates objects to dictionaries is the AnonymousObjectToHtmlAttributes
. It it's specifc to MVC and returns an RouteValueDictionary
, however.
If you want something more generic, try this:
public static IDictionary<string,object> AnonymousObjectToDictionary(object obj)
{
return TypeDescriptor.GetProperties(obj)
.OfType<PropertyDescriptor>()
.ToDictionary(
prop => prop.Name,
prop => prop.GetValue(obj)
);
}
One intersting advantages of this implementation is that it returns an empty dictionary for null
objects.
And here's one generic version:
public static IDictionary<string,T> AnonymousObjectToDictionary<T>(
object obj, Func<object,T> valueSelect
)
{
return TypeDescriptor.GetProperties(obj)
.OfType<PropertyDescriptor>()
.ToDictionary<PropertyDescriptor,string,T>(
prop => prop.Name,
prop => valueSelect(prop.GetValue(obj))
);
}
AsEnumerable()
here, most probably. It doesn't add anything on top ofSelect()
. – Ketosisobject
is not an anonymous type. – Vodka