What\'s the best way to merge 2 or more dictionaries (Dictionary
) in C#?
(3.0 features like LINQ are fine).
I\'m thinking of a method signa
Based on the answers above, but adding a Func-parameter to let the caller handle the duplicates:
public static Dictionary Merge(this IEnumerable> dicts,
Func, TValue> resolveDuplicates)
{
if (resolveDuplicates == null)
resolveDuplicates = new Func, TValue>(group => group.First());
return dicts.SelectMany, KeyValuePair>(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key, group => resolveDuplicates(group));
}