难点在于处理关键冲突的合并。
如果我们首先使用SelectMany
展开所有输入词典,那么我们可以通过键将它们组合在一起。
var result = dictionaries
.SelectMany(dict => dict)
.GroupBy(kvp => kvp.Key)
结果集包含基团,其中每个组的关键是从原来的字典的密钥,并且该组的内容具有相同的键的清单的IEnumerable<List<T>>
。从这些组中,我们可以将所有List<T>
合并成一个单独的IEnumerable<T>
,使用转换与SelectMany
。
var result = dictionaries
.SelectMany(dict => dict)
.GroupBy(kvp => kvp.Key)
.Select(grp => new { Key = grp.Key, Items = grp.SelectMany(list => list)})
然后,我们可以得到这样一个字典使用ToDictionary
改造,转换IEnumerable<T>
回List<T>
。
var result = dictionaries
.SelectMany(dict => dict)
.GroupBy(kvp => kvp.Key)
.Select(grp => new { Key = grp.Key, Items = grp.SelectMany(list => list)})
.ToDictionary(kip => kip.Key, kip => new List<T>(kip.Items));
更新回应置评
可以填充dictionaries
但是你喜欢。我假定它是一种类型,它实现IEnumerable<IDictionary<TKey, List<T>>>
为您选择的TKey
和T
。
最简单的方法将使用一个List<T>
如下:
List<IDictionary<TKey, List<T>>> dictionaries
= new List<IDictionary<TKey, List<T>>>();
dictionaries.Add(dictionary1); // Your variable
dictionaries.Add(dictionary2); // Your variable
// Add any other dictionaries here.
// Code as above!
如何填充'词典'? – 2010-01-25 14:57:32
更新了我的答案,包括如何填充“词典”变量。 – 2010-01-25 17:25:37