如何在C#中重复两个合并 [英] How to merge two didctionaries in C# with duplicates

查看:189
本文介绍了如何在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方法,请尝试: / p>

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,并带有一个Key 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天全站免登陆