2

可能重复:
在 C# 中合并字典

使用具有 2 个类型的字典的 c#4

<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]} 
              ]

所以得到=>

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

我该怎么做 ?

4

2 回答 2

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);
    }
}
于 2012-11-24T20:21:13.910 回答
2
var result = 
   dictionary1.Union(dictionary2)
    .GroupBy(kv => kv.Key)
    .ToDictionary(g => g.Key, g => g.SelectMany(v => v.Value).Distinct().ToList());
于 2012-11-24T20:33:43.060 回答