C#合并两个整数字典并添加重复项

时间:2017-08-04 14:44:52

标签: c#

我遇到类似以下帖子的问题:

  

How to merge two didctionaries in C# with duplicates

然而,在帖子中,解决方案连接重复的字符串。我想做类似的事情,但是用整数,我不想连接它们,我想添加它们。

所以我想要这个:

var firstDic = new Dictionary<string, int>  
{  
    {"apple", 1},  
    {"orange", 2}  
};

var secondDic = new Dictionary<string, int>
{
    {"apple", 3},
    {"banana", 4}
};

以某种方式结合成为:

var thirdDic = new Dictionary<string, int>
    {
        {"apple", 4},  //values from the two "apple" keys added together.
        {"orange", 2},  
        {"banana", 4}
    };

有没有快速简便的方法可以做到这一点,而不必做一些麻烦的嵌套循环混乱?

1 个答案:

答案 0 :(得分:5)

只需使用Sum

var thirdDic = firstDic.Concat(secondDic)
    .GroupBy(o => o.Key)
    .ToDictionary(o => o.Key, o => o.Sum(v => v.Value));