【问题标题】:LINQ Summary of Nested Dictionary嵌套字典的LINQ摘要
【发布时间】:2015-07-08 00:07:10
【问题描述】:

字典>

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

我怎样才能得到这些汇总结果

字典>

2015/6/1   table1  500,
           table2  600

2015/6/2   table1  200,
           table2  700

【问题讨论】:

  • 如何生成输出?在 DateTime 值上使用 .ToShortDateString()。

标签: c# linq dictionary nested


【解决方案1】:

您需要使用SelectMany 展平您的内部字典,然后您可以首先在日期时间应用GroupBy(在您的字典中为Key),结果您需要再次按tables 分组。最后,您可以将输出投影为字典。这是完整的代码:-

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);

Working Fiddle.

【讨论】:

  • 谢谢你,这对我帮助很大。我是 linq 的新手,SelectMany 将是下一个研究对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
相关资源
最近更新 更多