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"
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer.
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);
If you are using .NET 3.5 SP1 or .NET 4, you can (ab)use RouteValueDictionary
for this. It implements IDictionary<string, object>
and has a constructor that accepts object
and converts properties to key-value pairs.
It would then be trivial to loop through the keys and values to build your query string.
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