Convert Dictionary<string, object> To Anonymous Object?
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;
I tried to do this in one statement with a reduce function (Aggregate in Linq). The code below does the same as the accepted answer:
var dict = new Dictionary<string, object> { { "Property", "foo" } };
dynamic eo = dict.Aggregate(new ExpandoObject() as IDictionary<string, Object>,
(a, p) => { a.Add(p); return a; });
string value = eo.Property;