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
Note that if you use an extension method called 'Add', you get to use collection initializers to combine as many dictionaries as needed like this:
public static void Add(this Dictionary d, Dictionary other) {
foreach (var kvp in other)
{
if (!d.ContainsKey(kvp.Key))
{
d.Add(kvp.Key, kvp.Value);
}
}
}
var s0 = new Dictionary {
{ "A", "X"}
};
var s1 = new Dictionary {
{ "A", "X" },
{ "B", "Y" }
};
// Combine as many dictionaries and key pairs as needed
var a = new Dictionary {
s0, s1, s0, s1, s1, { "C", "Z" }
};