Created
March 28, 2012 00:02
-
-
Save theburningmonk/2221646 to your computer and use it in GitHub Desktop.
Dictionary to Expando
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Extension method that turns a dictionary of string and object to an ExpandoObject | |
/// </summary> | |
public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary) | |
{ | |
var expando = new ExpandoObject(); | |
var expandoDic = (IDictionary<string, object>)expando; | |
// go through the items in the dictionary and copy over the key value pairs) | |
foreach (var kvp in dictionary) | |
{ | |
// if the value can also be turned into an ExpandoObject, then do it! | |
if (kvp.Value is IDictionary<string, object>) | |
{ | |
var expandoValue = ((IDictionary<string, object>)kvp.Value).ToExpando(); | |
expandoDic.Add(kvp.Key, expandoValue); | |
} | |
else if (kvp.Value is ICollection) | |
{ | |
// iterate through the collection and convert any strin-object dictionaries | |
// along the way into expando objects | |
var itemList = new List<object>(); | |
foreach (var item in (ICollection)kvp.Value) | |
{ | |
if (item is IDictionary<string, object>) | |
{ | |
var expandoItem = ((IDictionary<string, object>)item).ToExpando(); | |
itemList.Add(expandoItem); | |
} | |
else | |
{ | |
itemList.Add(item); | |
} | |
} | |
expandoDic.Add(kvp.Key, itemList); | |
} | |
else | |
{ | |
expandoDic.Add(kvp); | |
} | |
} | |
return expando; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment