how to convert an instance of an anonymous type to a NameValueCollection
Asked Answered
B

4

15

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;
Breadthways answered 15/5, 2010 at 0:18 Comment(0)
G
29
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()));
Guarnerius answered 15/5, 2010 at 0:26 Comment(4)
how do you handle null value ?Tackle
@Tackle with song in my heart and a high quality pair of adult diapers. Where do you have the null?Guarnerius
@YuriyFaktorovich I get a null in some cases because you are calling .ToString() when in some cases pi.GetValue returns null. Changing it to pi.GetValue(vm, null)?.ToString() has allowed me to overcome it.Allseed
I am getting an error null object reference. thanks – solution of @sychich-rush works without error. thanksHamlin
M
5

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()));
Masbate answered 15/5, 2010 at 6:41 Comment(0)
P
3

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());
}
Peggypegma answered 15/5, 2010 at 0:24 Comment(3)
Using .ToList<T>.ForEach is faster than foreachGuarnerius
Good point. Forgot about that. But the real killer in my sln is the ToDictionary()Peggypegma
@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.)Masbate
H
1

I like the answer Yurity gave with one minor tweak to check for nulls.

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()));
Hominid answered 22/9, 2014 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.