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
@Tim: Should be a comment, but comments don't allow for code editing.
Dictionary t1 = new Dictionary();
t1.Add("a", "aaa");
Dictionary t2 = new Dictionary();
t2.Add("b", "bee");
Dictionary t3 = new Dictionary();
t3.Add("c", "cee");
t3.Add("d", "dee");
t3.Add("b", "bee");
Dictionary merged = t1.MergeLeft(t2, t2, t3);
Note: I applied the modification by @ANeves to the solution by @Andrew Orsich, so the MergeLeft looks like this now:
public static Dictionary MergeLeft(this Dictionary me, params IDictionary[] others)
{
var newMap = new Dictionary(me, me.Comparer);
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;
}