嵌套字典的LINQ摘要
本文关键字:摘要 LINQ 字典 嵌套 | 更新日期: 2023-09-27 18:01:25
Dictionary<DateTime,>>
2015/6/1 10:30 table1 300,
table2 600
2015/6/1 11:25 table1 200
2015/6/2 10:25 table1 200,
table2 700
我怎样才能得到这些总结结果
Dictionary<DateTime,>>
2015/6/1 table1 500,
table2 600
2015/6/2 table1 200,
table2 700
您需要使用SelectMany来平化您的内部字典,之后您可以在DateTime上首先应用GroupBy(字典中的Key
),并且在结果中您需要再次按tables
分组。最后,您可以将输出投影为Dictionary。下面是完整的代码:-
Dictionary<DateTime,Dictionary<string,double>> result =
data.SelectMany(x => x.Value, (key, obj) => new { key, obj })
.GroupBy(x => new { Date = x.key.Key.Date })
.Select(x => new
{
Date = x.Key.Date,
Output = x.GroupBy(z => z.obj.Key)
.Select(t => new { Table = t.Key, Sum = t.Sum(m => m.obj.Value) })
.ToDictionary(d => d.Table, d => d.Sum)
}).ToDictionary(x => x.Date, x=> x.Output);
工作小提琴。