Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
}
like image 317
Ramesh Durai Avatar asked Sep 14 '12 12:09

Ramesh Durai


1 Answers

Try with:

IEnumerable<object> values = testData.SelectMany(x => x.Values);
like image 138
Alessandro Avatar answered Nov 15 '22 09:11

Alessandro