問題描述
我有兩個結構相同的字典:
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# 中對兩個字典中的值求和?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!