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

How do I sum values from two dictionaries in C#?(如何在 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# 中对两个字典中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)