将值为字典的字典投影到值为聚合的新字典中
本文关键字:字典 新字典 投影 | 更新日期: 2023-09-27 18:26:43
我有以下格式的输入:
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。
由于您不需要父字典的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));
无分组依据:
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;
} );