views:

73

answers:

3

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"
+7  A: 

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);
kbrimington
+1 for the use of LINQ to get the properties.
Robaticus
+1  A: 

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.

GWB
+1 for reusing functionality already in the framework.
Bevan
I say "abuse" because the class was originally designed for routing (or at least its name and namespace imply this). However, it contains no routing-specific functionality and is already used for other features (like converting anonymous objects to dictionaries for HTML attributes in the ASP.NET MVC `HtmlHelper` extension methods.
GWB
+1  A: 

Here is how they do it in RouteValueDictionary:

  private void AddValues(object values)
    {
        if (values != null)
        {
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
            {
                object obj2 = descriptor.GetValue(values);
                this.Add(descriptor.Name, obj2);
            }
        }
    }

Full Source is here: http://pastebin.com/c1gQpBMG

John