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
Merging using an extension method. It does not throw exception when there are duplicate keys, but replaces those keys with keys from the second dictionary.
internal static class DictionaryExtensions
{
public static Dictionary Merge(this Dictionary first, Dictionary second)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
var merged = new Dictionary();
first.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
second.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
return merged;
}
}
Usage:
Dictionary merged = first.Merge(second);