合并两个字典但值加起来

merging two dictionaries but values adds up

我有两个字典,每个字典都有一个字符串作为键,一个整数作为值我想合并这两个字典,但是如果键重复,值就会加起来我有使用循环来填充的想法第三本字典,但有没有更简单的方法主要减少时间

提前谢谢你:D

您可以使用 Linq:

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass {
    public static void Main(string[] args) {
        IDictionary <string, int> dictA = new Dictionary <string, int>();
        dictA.Add("Apple", 2);
        dictA.Add("Banana", 1);

        IDictionary <string, int> dictB = new Dictionary <string, int>();
        dictB.Add("Apple", 1);
        dictB.Add("Cherry", 5);

        IDictionary <string, int> dictC = dictA.Concat(dictB)
            .GroupBy(i => i.Key)
            .ToDictionary(i => i.Key, i => i.Sum(j => j.Value));

        foreach(KeyValuePair <string, int> kvp in dictC) {
            Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
        }
    }
}

输出:

Key: Apple, Value: 3
Key: Banana, Value: 1
Key: Cherry, Value: 5