14

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;
east1000
  • 1,240
  • 1
  • 10
  • 30
Frank Schwieterman
  • 24,142
  • 15
  • 92
  • 130

4 Answers4

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()));
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • 1
    how do you handle null value ? – Kiddo May 09 '14 at 13:22
  • 1
    @Kiddo with song in my heart and a high quality pair of adult diapers. Where do you have the null? – Yuriy Faktorovich May 09 '14 at 14:55
  • 1
    @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. – ProNotion Mar 14 '18 at 12:56
  • I am getting an error null object reference. thanks – solution of @sychich-rush works without error. thanks – MindRoasterMir Sep 15 '21 at 07:42
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()));
LukeH
  • 263,068
  • 57
  • 365
  • 409
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());
}
Scott Weinstein
  • 18,890
  • 14
  • 78
  • 115
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()));
Psychic Rush
  • 360
  • 1
  • 3
  • 14