How do I sum values from two dictionaries in C#?(如何在 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# 中对两个字典中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中对两个字典中的值求和?
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01