O. Shai
O. Shai

Reputation: 813

Convert ParameterInfo[] to RouteValueDictionary via LINQ

Basically, I need to convert an array of ParameterInfo[] to a RouteValueDictionary, using LINQ.

I'm getting the ParameterInfo[] array from a MethodInfo object (via reflection), by calling obj.GetParameters(), and I need a RouteValueDictionary object from that.

I tried this, but unfortunately it is not working:

new RouteValueDictionary(obj.GetParameters().Select(r => new { r.Name = r.DefaultValue }))

Upvotes: 1

Views: 176

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

RouteValueDirectory has a constructor that gets a dictionary and:

Initializes a new instance of the RouteValueDictionary class and adds elements from the specified collection.

Therefore use linq's ToDictionary to form the dictionary and then the matching constructor:

new RouteValueDictionary(obj.GetParameters().ToDictionary(key => key.Name, 
                                                          value => value.DefaultValue }))

Upvotes: 2

Related Questions