合并字典包含列表在C#
这与此问题有关如何合并两个字典C#。
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< Object1,Object2>,
而我有一个字典,其值为 List< Object2>。
However, that question relates to Dictionary<Object1, Object2>,
whereas I have a dictionary where the value is a List<Object2>.
我正在寻找一个用于合并字典< Object1,List< Object2>,
的解决方案具有以下要求:
I am looking for a solution for merging a Dictionary<Object1, List<Object2>>,
with the following requirements:
- 如果Dictionary1包含与Dictionary2相同的密钥,那么他们的
List< Object2>
列表应该被组合。您将使用共享密钥和两个字典的组合列表结束一个新的键值对。 - 如果Dictionary1包含Dictionary2不存在的密钥,那么 List< Object2> 列表从Dictionary1应该成为值,反之亦然。
- 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中可能是不可能的,或者可能值得用循环等方式写出来,但是最好有一个优雅的解决方案。
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);
}
}