使用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]}
]
我该怎么办?
答案 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());