As you know, the ExpandoObject class implements the IDictionary<string, object> interface, so if you have an ExpandoObject you can easily cast it to an IDictionary<string, object> but there’s no built-in way to easily do the reverse.
Luckily, I came across a very useful extension method today which converts an IDictionary<string, object> into an ExpandoObject, which you can then use dynamically in your code, sweet! :-)
With some small modifications, here’s the code I ended up with, with some comments thrown in for good measures:
1: /// <summary>
2: /// Extension method that turns a dictionary of string and object to an ExpandoObject
3: /// </summary>
4: public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary)
5: {
6: var expando = new ExpandoObject();
7: var expandoDic = (IDictionary<string, object>)expando;
8:
9: // go through the items in the dictionary and copy over the key value pairs)
10: foreach (var kvp in dictionary)
11: {
12: // if the value can also be turned into an ExpandoObject, then do it!
13: if (kvp.Value is IDictionary<string, object>)
14: {
15: var expandoValue = ((IDictionary<string, object>)kvp.Value).ToExpando();
16: expandoDic.Add(kvp.Key, expandoValue);
17: }
18: else if (kvp.Value is ICollection)
19: {
20: // iterate through the collection and convert any strin-object dictionaries
21: // along the way into expando objects
22: var itemList = new List<object>();
23: foreach (var item in (ICollection)kvp.Value)
24: {
25: if (item is IDictionary<string, object>)
26: {
27: var expandoItem = ((IDictionary<string, object>) item).ToExpando();
28: itemList.Add(expandoItem);
29: }
30: else
31: {
32: itemList.Add(item);
33: }
34: }
35:
36: expandoDic.Add(kvp.Key, itemList);
37: }
38: else
39: {
40: expandoDic.Add(kvp);
41: }
42: }
43:
44: return expando;
45: }
Enjoy!




[…] By using some code borrowed from StackOverflow (not the accepted answer, but I like it) and theburningmonk.com, you put together a custom serializer for ExpandoObject and you can get something more typical of […]
Thank you, very useful!!
Simply AMAZING!!!!