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
This doesn't explode if there are multiple keys ("righter" keys replace "lefter" keys), can merge a number of dictionaries (if desired) and preserves the type (with the restriction that it requires a meaningful default public constructor):
public static class DictionaryExtensions
{
// Works in C#3/VS2008:
// Returns a new dictionary of this ... others merged leftward.
// Keeps the type of 'this', which must be default-instantiable.
// Example:
// result = map.MergeLeft(other1, other2, ...)
public static T MergeLeft(this T me, params IDictionary[] others)
where T : IDictionary, new()
{
T newMap = new T();
foreach (IDictionary 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;
}
}