Search code examples
c#anonymous-typesnamevaluecollection

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;

Solution

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