【问题标题】:C# Merge two dictionaries of integers and adding duplicatesC#合并两个整数字典并添加重复项
【发布时间】:2017-08-04 14:44:52
【问题描述】:

我有一个类似下面帖子的问题:

How to merge two didctionaries in C# with duplicates

但是,在帖子中,解决方案连接了重复的字符串。我想做类似的事情,但是使用整数,我不想连接它们,我想添加它们。

所以我想要这个:

var firstDic = new Dictionary<string, int>  
{  
    {"apple", 1},  
    {"orange", 2}  
};

var secondDic = new Dictionary<string, int>
{
    {"apple", 3},
    {"banana", 4}
};

以某种方式联合成为:

var thirdDic = new Dictionary<string, int>
    {
        {"apple", 4},  //values from the two "apple" keys added together.
        {"orange", 2},  
        {"banana", 4}
    };

有没有什么快速简便的方法可以做到这一点,而不必做一些麻烦的嵌套循环混乱?

【问题讨论】:

    标签: c#


    【解决方案1】:

    只需使用Sum:

    var thirdDic = firstDic.Concat(secondDic)
        .GroupBy(o => o.Key)
        .ToDictionary(o => o.Key, o => o.Sum(v => v.Value));
    

    【讨论】:

    • 您可以包含一个始终返回 false 的 IEqualityComparer。或者你可以使用 Concat 而不是 Union
    猜你喜欢
    • 2012-04-19
    • 2012-09-12
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    相关资源
    最近更新 更多