2

Possible Duplicate:
Merging dictionaries in C#

using c#4 having 2 dictionaries of type

<string,List<int>>



dictionary1 = [ { "key1" , [ 1, 2, 3]} ,
                 { "key2" , [ 1, 2, 4 , 6]}
              ]

I want to union with dictionary2

dictionary2 = [ { "key0" , [ 1, 2, 3]} ,
                 { "key2" , [ 1, 2, 3, 5 , 6]} 
              ]

so to get =>

dictionary1 + dictionary2  = [ { "key1" , [ 1, 2, 3]} ,
                 { "key2" , [ 1, 2, 3, 4, 5, 6]},
                 { "key0" , [ 1, 2, 3]}
              ]

how can I do it ?

Community
  • 1
  • 1
Haddar Macdasi
  • 3,477
  • 8
  • 37
  • 59

2 Answers2

5

A simple loop with Enumerable.Union?:

foreach (var kv in dictionary2)
{
    List<int> values;
    if (dictionary1.TryGetValue(kv.Key, out values))
    {
        dictionary1[kv.Key] = values.Union(kv.Value).ToList();
    }
    else
    {
        dictionary1.Add(kv.Key, kv.Value);
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2
var result = 
   dictionary1.Union(dictionary2)
    .GroupBy(kv => kv.Key)
    .ToDictionary(g => g.Key, g => g.SelectMany(v => v.Value).Distinct().ToList());
L.B
  • 114,136
  • 19
  • 178
  • 224