【问题标题】:Combine multiple dictionaries with same key in them into one dictionary with the sum of values将多个具有相同键的字典组合成一个字典,其中包含值的总和
【发布时间】:2015-11-15 03:16:46
【问题描述】:

输入

字典 1

"a", "1"

“b”、“2”

字典 2

“a”、“3”

“b”、“4”

字典 3

“a”、“5”

“b”、“6”

OUTPUT(上述字典的串联)

最终字典

“a”、“9”

“b”、“12”

我为此写了一个伪代码:

  1. 创建一个最终的空字典。
  2. 遍历字典列表。
  3. 循环遍历 KeyValue 对。
  4. 检查最终字典中是否存在该键。如果是,则将 KeyValue 对中的值添加到最终字典中。如果没有,则将 KeyValue 对添加到字典中

由于这需要两个 foreach 循环,因此在 c# 中有一个 lync 版本,它也不会引发任何异常。

我在stackoverflow上提到的一些问题是Combine multiple dictionaries into a single dictionary

【问题讨论】:

  • 好的,那么到目前为止,您编写了哪些代码,以及它以什么方式不起作用?
  • 字典 finaldict = new Dictionary(); foreach (KeyValuePair> kvp in Dictionary) { foreach (KeyValuePair dict in kvp.Value.AsEnumerable()) { Class1 tempClass1; finaldict.TryGetValue(dict.Key, out tempClass1); if (tempClass1 != null) { tempClass1.Increment(dict.Value.Counter); } else { finaldict.Add(dict.Key, dict.Value); } } }
  • 上面评论中的代码只是我在评论中提到的伪代码的核心逻辑。
  • 好的,但是你已经足够了解通常大多数人不会费心为你编写代码而不费力
  • @BugFinder 我完全同意你的观点,并且在我第一次编辑后无法编辑问题。一旦我能够编辑,就会将代码添加到问题中。

标签: c# dictionary


【解决方案1】:
var dict1 = new Dictionary<string, int>() { { "a", 1 }, { "b", 2 } };
var dict2 = new Dictionary<string, int>() { { "a", 3 }, { "b", 4 } };
var dict3 = new Dictionary<string, int>() { { "a", 5 }, { "b", 6 } };

var resDict = dict1.Concat(dict2)
                   .Concat(dict3)
                   .GroupBy(x => x.Key)
                   .ToDictionary(x => x.Key, x => x.Sum(y=>y.Value));

【讨论】:

  • 这是我所问问题的正确答案。下面@Martin 的回答适用于任意数量的词典,因此将其标记为正确。感谢 Eser 抽出宝贵时间回答问题
【解决方案2】:

您可以使用SelectMany 将每个字典中的所有键值对连接到一个序列中,然后您可以按键分组并对每个键的值求和以确定最终值:

var dictionaries = new[] {
  new Dictionary<String, Int32>() { { "a", 1 }, { "b", 2 } },
  new Dictionary<String, Int32>() { { "a", 3 }, { "b", 4 } },
  new Dictionary<String, Int32>() { { "a", 5 }, { "b", 6 } }
};

var result = dictionaries
  .SelectMany(d => d)
  .GroupBy(
    kvp => kvp.Key,
    (key, kvps) => new { Key = key, Value = kvps.Sum(kvp => kvp.Value) }
  )
  .ToDictionary(x => x.Key, x => x.Value);

此解决方案适用于任意数量的字典 - 不仅仅是固定的字典集。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多