難點在於處理關鍵衝突的合併。
如果我們首先使用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