How to combine two dictionaries in C # with duplicates
Is there a way in C # to combine two dictionaries? I have two dictionaries that may have the same keys, but I'm looking for a way to merge them, so at the end there is a dictionary with the same key and values from both dictionaries. I found the following code, but it doesn't handle duplicates.
Dictionary Mydictionary<string, string[]> = new Dictionary<string, string[]>();
Mydictonary.Union(secondDictionary).ToDictionary( pair => pair.Key, pair => pair.Value);
+2
a source to share
3 answers
If you need 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());
For this example, you will get a dictionary with 3 KeyValuePairs, and the item with key "apple" will have an array with "red" and "green" for the value.
+2
a source to share
This should do it:
Dictionary<string, string[]> dict1 = new Dictionary<string, string[]>();
Dictionary<string, string[]> dict2 = new Dictionary<string, string[]>();
Dictionary<string, List<string>> combined = new Dictionary<string, List<string>>();
foreach (var pair in dict1) combined.Add(pair.Key, new List<string>(pair.Value));
foreach (var pair in dict2)
{
List<string> list;
if (!combined.TryGetValue(pair.Key, out list)) combined.Add(pair.Key, list = new List<string>());
list.AddRange(pair.Value);
}
If you really want to get the result like Dictionary<string, string[]>
, you can do it all the way:
Dictionary<string, string[]> combinedArray = new Dictionary<string, string[]>();
foreach (var pair in combined) combinedArray.Add(pair.Key, pair.Value.ToArray());
0
a source to share