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

Chris Kooken picture Chris Kooken · Aug 14, 2010 · Viewed 41.3k times · Source

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"

Answer

kbrimington picture kbrimington · Aug 14, 2010

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