Getting Keys and Values from IEnumerable<Dictionary<string, object>>

Ramesh Durai picture Ramesh Durai · Sep 14, 2012 · Viewed 16.9k times · Source

I have a IEnumerable < Dictionary < string, object > > object.

I want to get the "aaavalue" "bbbvalue" "cccvalue" "dddvalue" in a array.

Sample Data:

IEnumerable<Dictionary<string, object>> testData = new IEnumerable<Dictionary<string, object>>();

/* Values in testData will be like
   [0] - 
         aaa - aaaValue   (Key, Value)
         bbb - bbbValue
         ccc - cccValue
         ddd - dddValue  
   [1] - 
         aaa - aaaValue   (Key, Value)
         bbb - bbbValue
         ccc - cccValue
         ddd - dddValue  

    and so on */

I know it is possible using Reflection or LINQ. But I could not able to make it up.

Please help..

Answer:

IEnumerable<Dictionary<string, object>> enumerable = testData as List<Dictionary<string, object>> ?? testData .ToList();
foreach (Dictionary<string, object> objects in enumerable)
{
    IEnumerable<object> values = objects.Select(x => x.Value); // To get the values.
    IEnumerable<string> keys = objects.Select(x => x.Key); // To get the keys.
}

Answer

Alessandro picture Alessandro · Sep 14, 2012

Try with:

IEnumerable<object> values = testData.SelectMany(x => x.Values);