Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
like image 538
Chris Kooken Avatar asked Aug 14 '10 03:08

Chris Kooken


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What does %d do in C?

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.


2 Answers

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); 
like image 53
kbrimington Avatar answered Sep 24 '22 20:09

kbrimington


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.

like image 45
GWB Avatar answered Sep 25 '22 20:09

GWB