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;
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()));