如何在C#中对两个词典中的值求和?

Geo*_*ker 12 .net c# linq dictionary sum

我有两个结构相同的词典:

Dictionary<string, int> foo = new Dictionary<string, int>() 
{
    {"Table", 5 },
    {"Chair", 3 },
    {"Couch", 1 }
};

Dictionary<string, int> bar = new Dictionary<string, int>() 
{
    {"Table", 4 },
    {"Chair", 7 },
    {"Couch", 8 }
};
Run Code Online (Sandbox Code Playgroud)

我想将字典的值加在一起,并返回带有键的第三个字典,以及每个键的总值:

Table, 9
Chair, 10
Couch, 9
Run Code Online (Sandbox Code Playgroud)

我目前的解决方案是循环遍历字典并以这种方式将其拉出来,但我知道解决方案不是性能最高或最易读的.然而,我正试图在LINQ中找到解决方案.

Tom*_*cek 15

以下不是最有效的解决方案(因为它只是将两个词典都视为枚举),但它会起作用并且非常清楚:

Dictionary<string, int> result = (from e in foo.Concat(bar)
              group e by e.Key into g
              select new { Name = g.Key, Count = g.Sum(kvp => kvp.Value) })
              .ToDictionary(item => item.Name, item => item.Count);
Run Code Online (Sandbox Code Playgroud)


Car*_*los 5

如果您有铸铁保证两套钥匙相同:

Dictionary<string, int> Res2 = foo.ToDictionary(orig => orig.Key, orig => orig.Value + bar[orig.Key]);
Run Code Online (Sandbox Code Playgroud)

如果键设置不同,我能想到的最好方法是:

var AllKeys = foo.Keys.Union(bar.Keys);
var res3 = AllKeys.ToDictionary(key => key,  key => (foo.Keys.Contains(key)?foo[key] : 0) + (bar.Keys.Contains(key)?bar[key] : 0));
Run Code Online (Sandbox Code Playgroud)