你应该问自己的第一个问题:合并两个字典的结果有什么类型?如果它们共享相同的键,如何将值合并在一起?
它可能是这样的:
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
}
这需要 aIEnumerable<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));