从IEnumerable获取键和值<dictionary <string,object =“”>&gt; </dictionary <string,>

时间:2012-09-14 12:56:11

标签: c# linq .net-4.0 dictionary system.reflection

我有一个 IEnumerable < Dictionary < string, object > > 对象。

我想在数组中获得“aaavalue”“bbbvalue”“cccvalue”“dddvalue”。

示例数据:

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 */

我知道可以使用Reflection或LINQ。但我无法弥补。

请帮助..

答案:

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.
}

1 个答案:

答案 0 :(得分:7)

尝试:

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