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
A version from @user166390 answer with an added IEqualityComparer
parameter to allow for case insensitive key comparison.
public static T MergeLeft(this T me, params Dictionary[] others)
where T : Dictionary, new()
{
return me.MergeLeft(me.Comparer, others);
}
public static T MergeLeft(this T me, IEqualityComparer comparer, params Dictionary[] others)
where T : Dictionary, new()
{
T newMap = Activator.CreateInstance(typeof(T), new object[] { comparer }) as T;
foreach (Dictionary src in
(new List> { me }).Concat(others))
{
// ^-- echk. Not quite there type-system.
foreach (KeyValuePair p in src)
{
newMap[p.Key] = p.Value;
}
}
return newMap;
}