Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way of converting a RouteValueDictionary to an anonymous object?

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"}
like image 493
Matthew Bonig Avatar asked Sep 23 '11 01:09

Matthew Bonig


2 Answers

This isn't possible to do at run-time. The properties for an anonymous type need to be known beforehand, at compile-time.

like image 115
Mark Cidade Avatar answered Sep 21 '22 11:09

Mark Cidade


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) });
like image 32
Rich O'Kelly Avatar answered Sep 21 '22 11:09

Rich O'Kelly