IDictionary<string, object> to ExpandoObject extension method

As you know, the ExpandoOb­ject class imple­ments the IDictionary<string, object> inter­face, so if you have an ExpandoOb­ject you can eas­i­ly cast it to an IDictionary<string, object> but there’s no built-in way to eas­i­ly do the reverse.

Luck­i­ly, I came across a very use­ful exten­sion method today which con­verts an IDictionary<string, object> into an ExpandoOb­ject, which you can then use dynam­i­cal­ly in your code, sweet! :-)

With some small mod­i­fi­ca­tions, here’s the code I end­ed up with, with some com­ments thrown in for good mea­sures:

   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!