转换字典<string,list <object =“”>&gt;在LINQ </dictionary <string,> </string,>中列出<dictionary <string,object =“”>

时间:2013-04-19 16:02:58

标签: linq list dictionary

如何在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

2 个答案:

答案 0 :(得分: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();

查看demo on ideone

答案 1 :(得分:0)

我会给你更简单的选择,而不会使用聚合:

var target = Enumerable.Range(0, source.Values.First().Count)
                   .Select(i => source.ToDictionary(x => x.Key, x => x.Value[i]))
                   .ToList();