how to union 2 dictionaries
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Merging dictionaries in C#
号
使用C 4,有两个类型的字典
1 2 3 4 5 6 7 | <string,List<int>> dictionary1 = [ {"key1" , [ 1, 2, 3]} , {"key2" , [ 1, 2, 4 , 6]} ] |
我想和字典结合2
1 2 3 | dictionary2 = [ {"key0" , [ 1, 2, 3]} , {"key2" , [ 1, 2, 3, 5 , 6]} ] |
号
所以要得到=>
1 2 3 4 | dictionary1 + dictionary2 = [ {"key1" , [ 1, 2, 3]} , {"key2" , [ 1, 2, 3, 4, 5, 6]}, {"key0" , [ 1, 2, 3]} ] |
我该怎么做?
一个带有
1 2 3 4 5 6 7 8 9 10 11 12 | 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 3 4 | var result = dictionary1.Union(dictionary2) .GroupBy(kv => kv.Key) .ToDictionary(g => g.Key, g => g.SelectMany(v => v.Value).Distinct().ToList()); |
号