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) });
source share