你應該問自己的第一個問題:合併兩個字典的結果有哪些類型?如果價值共享相同的密鑰,價值如何合併在一起?
這可能是這樣的:
public static Dictionary<TKey, IEnumerable<TValue>> Merge<TKey, TValue>(this IDictionary<TKey, TValue> this_, IDictionary<TKey, TValue> other)
{
return this_.Concat(other). // IEnumerable<KeyValuePair<TKey, TValue>>
GroupBy(kvp => kvp.Key). // grouped by the keys
ToDictionary(grp => grp.Key, grp => grp.Select(kvp => kvp.Value).Distinct());
}
所以你Dictionary<string, Dictionary<string, object>>
型的兩個庫會去Dictionary<string, IEnumerable<Dictionary<string, object>>>
。
然而,你的價值觀是字典,所以你可能想將它們合併:
public static Dictionary<TKey, IEnumerable<TValue>> Flatten<TKey, TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)
{
return dictionaries.SelectMany(d => d.Keys).Distinct(). // IEnumerable<TKey> containing all the keys
ToDictionary(key => key,
key => dictionaries.Where(d => d.ContainsKey(key)). // find Dictionaries that contain the key
Select(d => d.First(kvp => kvp.Key.Equals(key))). // select that key (KeyValuePair<TKey, TValue>)
Select(kvp => kvp.Value)); // and the value
}
這需要一個IEnumerable<Dictionary<string, object>>
並將其轉換爲一個Dictionary<string, IEnumerable<object>>
。您現在可以針對Merge
生成的每個字典值調用此方法。
的呼聲是:
Dictionary<string, IEnumerable<Dictionary<string, object>>> result1 = dic1.Merge(dic2);
Dictionary<string, Dictionary<string, IEnumerable<object>>> result2 = dic1.Merge(dic2).ToDictionary(kvp => kvp.Key, kvp => Flatten(kvp.Value));
已經我堅持,我試圖做任何事,我還在找 – 2013-02-13 10:42:56
請告訴我們您嘗試過,所以我們可以在其上展開的。 – 2013-02-13 10:43:59
我改變了我的要求 – 2013-02-13 11:01:43