I have a MVC3 RouteValueDictionary that I'd like to convert quickly to an anonymous type.
for example:
new RouteValueDictionary(){{"action","search"}}
would be the same as
new {action="search"}
This isn't possible to do at run-time. The properties for an anonymous type need to be known beforehand, at compile-time.
NB this answer is caveated by the fact that I think it is interesting, however this probably (definitely) shouldn't be used for production code.
If you're able to construct an anonymous type (a template) that has all of the dictionary keys you are interested in, then you could use the following method:
public static class RouteValueDictionaryExtensions
{
public static TTemplate ToAnonymousType<TTemplate>(this RouteValueDictionary dictionary, TTemplate prototype)
{
var constructor = typeof(TTemplate).GetConstructors().Single();
var args = from parameter in constructor.GetParameters()
let val = dictionary.GetValueOrDefault(parameter.Name)
select val != null && parameter.ParameterType.IsAssignableFrom(val.GetType()) ? (object) val : null;
return (T) constructor.Invoke(args.ToArray());
}
}
Which would then be useable like so:
var dictionary = new RouteValueDictionary {{"action", "search"}};
var anonymous = dictionary.ToAnonymousType(new { action = default(string) });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With