Fast way to convert RouteValueDictionary to an anonymous object?

I have an MVC3 RouteValueDictionary that I would like to convert quickly to an anonymous type.

eg:

new RouteValueDictionary(){{"action","search"}} 

will be the same as

 new {action="search"} 
+4
source share
2 answers

This cannot be done at runtime. Properties for an anonymous type must be known in advance at compile time.

+5
source

NB, this answer is reinforced by the fact that I think it is interesting, however it probably (definitely) should not be used for production code.

If you can create an anonymous type (template) that has all the dictionary keys that interest you, you can 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()); } } 

What then could be used like this:

 var dictionary = new RouteValueDictionary {{"action", "search"}}; var anonymous = dictionary.ToAnonymousType(new { action = default(string) }); 
+1
source

All Articles