项目字典,其值是新字典中的字典,其值为聚合

时间:2014-10-15 19:42:20

标签: c# linq

我的输入格式如下:

var input = new Dictionary<int, Dictionary<string, int>>
{
    { 0, new Dictionary<string, int> { { "January", 10 }, { "February", 2 } } },
    { 1, new Dictionary<string, int> { { "January", 15 }, { "February", 4 } } },
    { 2, new Dictionary<string, int> { { "January", 5 }, { "February", 16 } } }
};

我想将此转换为Dictionary<string, int>类型的变量,其中每个值都是内部字典中值的总和。对于给出的示例,输出应为:

var output = new Dictionary<string, int> { { "January", 30 }, { "February", 22 } };

我怎样才能做到这一点?如果可能的话,LINQ会更好。

2 个答案:

答案 0 :(得分:4)

由于您不需要key父词典,您可以使用SelectMany展平内部词典,然后根据内部词典的Key对其进行分组,如:

 Dictionary<string, int> dictionary =  
                          input.SelectMany(r => r.Value)
                          .GroupBy(r => r.Key)
                          .ToDictionary(grp => grp.Key, grp => grp.Sum(t => t.Value));

答案 1 :(得分:1)

没有分组:

 input.SelectMany((x) => x.Value)
    .Aggregate( new Dictionary<string,int>(),
      (old,next) => 
       { old[next.Key] = old.ContainsKey(next.Key) ? old[next.Key] + next.Value : next.Value; 
         return old;
       } );