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;
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.
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()));
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With