将具有相同键的多个词典组合成一个具有值之和的字典 [英] Combine multiple dictionaries with same key in them into one dictionary with the sum of values
问题描述
INPUT
词典1
a,1
"a", "1"
b,2
词典2
a,3
"a", "3"
b ,4
词典3
a,5
"a", "5"
b,6
OUTPUT(上述字典的连接)
OUTPUT (Concatenation of the dictionaries above)
最终字典
a,9
"a", "9"
b,12
我写了一个伪代码:
- 创建一个Final空字典。
- 环绕字典列表。
- 循环使用KeyValue对。
- 检查密钥是否存在于最终的字典中。如果是,则将值从KeyValue对添加到最终字典。如果没有,然后添加到字典KeyValue对
- Create a Final empty dictionary.
- Loop over the list of dictionaries.
- Loop over the KeyValue pair.
- Check if the key exists in final dictionary. If yes then add the value from KeyValue pair to final dictionary. If not then add to dictionary the KeyValue pair
由于这需要两个foreach循环是c#中的lync版本,没有任何例外。
Since this requires two foreach loops is there a lync version in c# for this and also which doesn't throw any exception.
我在stackoverflow上提到的一些问题是将多个词典组合成单个字典
Some of the questions that i referred on stackoverflow was Combine multiple dictionaries into a single dictionary
推荐答案
您可以使用 SelectMany
将每个字典的所有键值对加入到单个序列中,然后您可以按键分组,并对每个键的值进行求和,以确定最终的值值:
You can use SelectMany
to join all the key-value pairs from each dictionary into a single sequence that you then can group by key and sum the values for each key to determine the final value:
var dictionaries = new[] {
new Dictionary<String, Int32>() { { "a", 1 }, { "b", 2 } },
new Dictionary<String, Int32>() { { "a", 3 }, { "b", 4 } },
new Dictionary<String, Int32>() { { "a", 5 }, { "b", 6 } }
};
var result = dictionaries
.SelectMany(d => d)
.GroupBy(
kvp => kvp.Key,
(key, kvps) => new { Key = key, Value = kvps.Sum(kvp => kvp.Value) }
)
.ToDictionary(x => x.Key, x => x.Value);
此解决方案适用于任何数量的字典 - 不仅仅是固定的字典集。
This solution works with any number of dictionaries - not just fixed set of dictionaries.
这篇关于将具有相同键的多个词典组合成一个具有值之和的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!