2017-08-04 88 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