4

如何在 LINQ中转换Dictionary<string, List<object>>为?List<Dictionary<string, object>我正在使用 for 循环进行操作,有什么方法可以以紧凑的方式进行操作吗?

Dictionary<string, List<object>> mydata = new Dictionary<string, List<object>>();
List<object> ldate=new List<object>(){"1/1/2000","1,1/2001"};
List<object> lage=new List<object>(){"4","5"};

mydata["date"] = ldate;
mydata["age"] = lage;

List<Dictionary<string, object>> mytarget = new List<Dictionary<string, object>>();
Dictionary<string,object> t1=new Dictionary<string,object>();
Dictionary<string,object> t2=new Dictionary<string,object>();

t1["date"]="1/1/2000";
t1["age"]="4";

t2["date"]="1/1/2001";
t2["age"]="5";

mytarget.Add(t1);
mytarget.Add(t2);

非常感谢,canric

4

2 回答 2

1

这应该有效:

Dictionary<string,List<object>> orig = ...
var res = Enumerable.Range(0, orig.Values.First().Count)
    .Select(
        i => orig.Aggregate(
            new Dictionary<string,object>()
        ,   (d, p) => { d[p.Key] = p.Value[i]; return d; }
        )
    ).ToList();

在 ideone 上查看演示。

于 2013-04-19T16:19:22.830 回答
0

我只会给你更简单的选择,而不需要复杂的聚合用法:

var target = Enumerable.Range(0, source.Values.First().Count)
                   .Select(i => source.ToDictionary(x => x.Key, x => x.Value[i]))
                   .ToList();
于 2013-04-19T17:26:45.587 回答