views:

142

answers:

3

Suppose I have an anonymous class instance

var foo = new { A = 1, B = 2};

Is there a quick way to generate a NameValueCollection? I would like to achieve the same result as the code below, without knowing the anonymous type's properties in advance.

NameValueCollection formFields = new NameValueCollection();
formFields["A"] = 1;
formFields["B"] = 2;
+1  A: 

Just about what you want:

Dictionary<string, object> dict = 
       foo.GetType()
          .GetProperties()
          .ToDictionary(pi => pi.Name, pi => pi.GetValue(foo, null));

NameValueCollection nvc = new NameValueCollection();
foreach (KeyValuePair<string, object> item in dict)
{
   nvc.Add(item.Key, item.Value.ToString());
}
Scott Weinstein
Using .ToList<T>.ForEach is faster than foreach
Yuriy Faktorovich
Good point. Forgot about that. But the real killer in my sln is the ToDictionary()
Scott Weinstein
@Yuriy: If we're worrying about micro-optimisation then using `Array.ForEach` will be faster still, and doesn't require the intermediate `ToList` pass. (See my answer for an example.)
LukeH
+3  A: 
var foo = new { A = 1, B = 2 };

NameValueCollection formFields = new NameValueCollection();

foo.GetType().GetProperties()
    .ToList()
    .ForEach(pi => formFields.Add(pi.Name, pi.GetValue(foo, null).ToString()));
Yuriy Faktorovich
too fast for me. verbatim except name of nvc. good job.
Sky Sanders
Just copying his code probably got me the few extra seconds.
Yuriy Faktorovich
+1  A: 

Another (minor) variation, using the static Array.ForEach method to loop through the properties...

var foo = new { A = 1, B = 2 };

var formFields = new NameValueCollection();
Array.ForEach(foo.GetType().GetProperties(),
    pi => formFields.Add(pi.Name, pi.GetValue(foo, null).ToString()));
LukeH