困难在于处理关键冲突的合并。
如果我们首先使用SelectMany 展平所有输入字典,我们可以按元素的键将元素组合在一起。
var result = dictionaries
.SelectMany(dict => dict)
.GroupBy(kvp => kvp.Key)
结果集包含组,其中每个组的键是原始字典中的键,组的内容是具有相同键的列表的IEnumerable<List<T>>。从这些组中,我们可以使用带有SelectMany 的Select 转换将所有List<T> 合并为一个IEnumerable<T>。
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。我假设它是一种为您选择的TKey 和T 实现IEnumerable<IDictionary<TKey, List<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!