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
The party's pretty much dead now, but here's an "improved" version of user166390 that made its way into my extension library. Apart from some details, I added a delegate to calculate the merged value.
///
/// Merges a dictionary against an array of other dictionaries.
///
/// The type of the resulting dictionary.
/// The type of the key in the resulting dictionary.
/// The type of the value in the resulting dictionary.
/// The source dictionary.
/// A delegate returning the merged value. (Parameters in order: The current key, The current value, The previous value)
/// Dictionaries to merge against.
/// The merged dictionary.
public static TResult MergeLeft(
this TResult source,
Func mergeBehavior,
params IDictionary[] mergers)
where TResult : IDictionary, new()
{
var result = new TResult();
var sources = new List> { source }
.Concat(mergers);
foreach (var kv in sources.SelectMany(src => src))
{
TValue previousValue;
result.TryGetValue(kv.Key, out previousValue);
result[kv.Key] = mergeBehavior(kv.Key, kv.Value, previousValue);
}
return result;
}