Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert an instance of an anonymous type to a NameValueCollection

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;
like image 496
Frank Schwieterman Avatar asked May 15 '10 00:05

Frank Schwieterman


People also ask

How do I change my class type to Anonymous?

Convert anonymous type(s) into a named type Place the caret at either anonymous type initializer or at the new keyword. Do one of the following: Press Ctrl+Shift+R and then choose Replace Anonymous Type with Named Class. Choose Refactor | Replace Anonymous Type with Named Class from the main menu.


2 Answers

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()));
like image 53
Yuriy Faktorovich Avatar answered Oct 06 '22 23:10

Yuriy Faktorovich


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()));
like image 31
LukeH Avatar answered Oct 07 '22 01:10

LukeH