如何结合2个字典

时间:2012-11-24 20:14:52

标签: c# dictionary

  

可能重复:
  Merging dictionaries in C#

使用c#4,其中包含2个类型为

的词典
<string,List<int>>



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

我想与dictionary2结合

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

所以得到=&gt;

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

我该怎么办?

2 个答案:

答案 0 :(得分:5)

使用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);
    }
}

答案 1 :(得分:2)

var result = 
   dictionary1.Union(dictionary2)
    .GroupBy(kv => kv.Key)
    .ToDictionary(g => g.Key, g => g.SelectMany(v => v.Value).Distinct().ToList());