2017-08-04 108 views
-2

我有类似下面的帖子一个问题: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} 
    }; 

有没有快速简便的方法来做到这一点,而不必做一些繁琐的嵌套循环烂摊子?

回答

5

只需使用Sum

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

不工会删除重复? –

+0

您可以包含始终返回false的IEqualityComparer。或者你可以使用Concat而不是Union – user2023861

+0

@ johnny5来自链接问题的傻副本错误,谢谢。 – DavidG