在 C# 中合并包含列表的字典 [英] Merging Dictionary containing a List in C#

查看:20
本文介绍了在 C# 中合并包含列表的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与这个问题有点相关,关于如何将两个字典合并到C#.提供了一个优雅的 Linq 解决方案,很酷.

This is kind-of related to this question, on how to merge two dictionaries in C#. An elegant Linq solution is presented, which is cool.

然而,这个问题与Dictionary,有关,而我有一个字典,其中的值是一个List.

However, that question relates to Dictionary<Object1, Object2>, whereas I have a dictionary where the value is a List<Object2>.

我正在寻找一种解决方案来合并具有以下要求的 Dictionary>,:

I am looking for a solution for merging a Dictionary<Object1, List<Object2>>, with the following requirements:

  • 如果 Dictionary1 包含与 Dictionary2 相同的键,那么它们的 List 列表应该被合并.您最终会得到一个带有共享键的新键值对,以及来自两个字典的组合列表.
  • 如果 Dictionary1 包含 Dictionary2 没有的键,则 Dictionary1 中的 List 列表应该成为值,反之亦然.
  • If Dictionary1 contains the same key as Dictionary2, then their List<Object2> lists should be combined. You would end up with a new key-value-pair with the shared key, and the combined lists from the two dictionaries.
  • If Dictionary1 contains a key that Dictionary2 doesn't then the List<Object2> list from Dictionary1 should become the value, and vice versa.

这在 Linq 中可能是不可能的,或者可能值得用 for 循环等直接写出来,但如果有一个优雅的解决方案会很好.

This may not be possible in Linq, or it may be worth writing it out longhand with for loops and the like, but it would be nice to have an elegant solution.

推荐答案

我建议创建您自己的扩展方法.会更高效,更容易修改.

I would suggest creating your own extension method. It will be more efficient and easier to modify.

public static void MergeDictionaries<OBJ1, OBJ2>(this IDictionary<OBJ1, List<OBJ2>> dict1, IDictionary<OBJ1, List<OBJ2>> dict2)
    {
        foreach (var kvp2 in dict2)
        {
            // If the dictionary already contains the key then merge them
            if (dict1.ContainsKey(kvp2.Key))
            {
                dict1[kvp2.Key].AddRange(kvp2.Value);
                continue;
            }
            dict1.Add(kvp2);
        }
    }

这篇关于在 C# 中合并包含列表的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆