Search code examples
c#.nethttpwebrequestanonymous-types

In c# convert anonymous type into key/value array?


I have the following anonymous type:

new {data1 = "test1", data2 = "sam", data3 = "bob"}

I need a method that will take this in, and output key value pairs in an array or dictionary.

My goal is to use this as post data in an HttpRequest so i will eventually concatenate in into the following string:

"data1=test1&data2=sam&data3=bob"

Solution

  • This takes just a tiny bit of reflection to accomplish.

    var a = new { data1 = "test1", data2 = "sam", data3 = "bob" };
    var type = a.GetType();
    var props = type.GetProperties();
    var pairs = props.Select(x => x.Name + "=" + x.GetValue(a, null)).ToArray();
    var result = string.Join("&", pairs);