如何在C#中将两个词典与重复项合并 [英] How to merge two dictionaries in C# with duplicates

查看:95
本文介绍了如何在C#中将两个词典与重复项合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中是否有一种方法可以合并两个字典?我有两个可能具有相同键的字典,但是我正在寻找一种合并它们的方法,因此,最后有一个带有一个键的字典,并且两个字典中的值都合并了. 我找到了以下代码,但它不能处理重复的代码.

Is there a way in C# to merge two dictionaries? I have two dictionaries that may has the same keys, but I am looking for a way to merge them so, in the end there is a dictionary with one key and the values from both the dictionaries merged. I found the following code but it does not handle duplicates.

Dictionary Mydictionary<string, string[]> = new Dictionary<string, string[]>();
Mydictonary.Union(secondDictionary).ToDictionary( pair => pair.Key, pair => pair.Value);

推荐答案

如果您要使用LINQ方法,请尝试以下操作:

If you want a LINQ approach, try this:

Dictionary<string, string[]> firstDic = new Dictionary<string, string[]>  
{  
    {"apple", new [] {"red"}},  
    {"orange", new [] {"orange"}}  
};

Dictionary<string, string[]> secondDic = new Dictionary<string, string[]>
{
    {"apple", new [] {"green"}},
    {"banana", new [] {"yellow"}}
};

Dictionary<string, string[]> resultDic = firstDic.Union(secondDic)
    .GroupBy(o => o.Key)
    .ToDictionary(o => o.Key, o => o.SelectMany(kvp => kvp.Value).ToArray());

对于示例数据,您将获得一个包含3个KeyValuePairs的Dictionary,并且键为"apple"的项将具有一个值分别为"red"和"green"的数组.

For the sample data, you'll get a Dictionary with 3 KeyValuePairs, and the item with a Key of "apple" will have an Array with "red" and "green" for the value.

这篇关于如何在C#中将两个词典与重复项合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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