如何在C#中将两个字典中的值相加? [英] How do I sum values from two dictionaries in C#?

查看:804
本文介绍了如何在C#中将两个字典中的值相加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two dictionaries with the same structure:

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 }
};

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

I'd like to sum the values of the dictionaries together and return a third dictionaries with the keys, and the total values for each key:

Table, 9
Chair, 10
Couch, 9

我当前的解决方案是遍历字典并以这种方式将它们拉出,但我知道该解决方案并不是性能最高或可读性最强的解决方案.但是,我遇到了难题,试图在LINQ中提出解决方案.

My current solution is to loop through the dictionary and pull them out that way, but I know that solution isn't the most performant or most readable. However, I'm hitting a brick wall trying to come up with a solution in LINQ.

推荐答案

以下不是最有效的解决方案(因为它只是将两个字典都视为可枚举的),但是它可以工作,而且很清楚:

The following isn't the most efficient solution (because it simply treats both dictionaries as enumerables), but it will work and it is quite clear:

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);

这篇关于如何在C#中将两个字典中的值相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆