Convert Dictionary<string, object> To Anonymous Object?

Kassem picture Kassem · Sep 29, 2011 · Viewed 65.2k times · Source

First, and to make things clearer I'll explain my scenario from the top:

I have a method which has the following signature:

public virtual void SendEmail(String from, List<String> recepients, Object model)

What I want to do is generate an anonymous object which has the properties of the model object along with the first two parameters as well. Flattening the model object into a PropertyInfo[] is very straightforward. Accordingly, I thought of creating a Dictionary which would hold the PropertyInfo's and the first two params, and then be converted into the anonymous object where the key is the name of the property and the value is the actual value of the property.

Is that possible? Any other suggestions?

Answer

svick picture svick · Sep 29, 2011

If you really want to convert the dictionary to an object that has the items of the dictionary as properties, you can use ExpandoObject:

var dict = new Dictionary<string, object> { { "Property", "foo" } };
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>)eo;

foreach (var kvp in dict)
{
    eoColl.Add(kvp);
}

dynamic eoDynamic = eo;

string value = eoDynamic.Property;

But I'm not sure how is doing that going to help you.