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#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01