Merge two dictionaries in-place in C#

By FoxLearn 3/20/2025 1:57:16 AM   55
When merging two dictionaries, you have the option to either perform the merge in-place or create a new dictionary and copy the values over.

The following extension method performs an in-place merge, iterating over items in the right dictionary and adding them to the left. If duplicate keys are encountered, it preserves the value from the left dictionary, instead of throwing an ArgumentException or keeping the value from the right.

public static class Helper
{
    public static Dictionary<Key, Value> MergeInPlace<Key, Value>(this Dictionary<Key, Value> left, Dictionary<Key, Value> right)
    {
        if (left == null)
        {
            throw new ArgumentNullException("Cannot merge into a null dictionary");
        }
        else if (right == null)
        {
            return left;
        }

        foreach (var kvp in right)
        {
            if (!left.ContainsKey(kvp.Key))
            {
                left.Add(kvp.Key, kvp.Value);
            }
        }

        return left;
    }
}

Note: While this method performs an in-place merge, it returns the dictionary, enabling fluent method chaining like: left.MergeInPlace(dict1).MergeInPlace(dict2).Count().

Why Not Use LINQ Union() or Concat()?

You might wonder why you need a custom merge method instead of using LINQ's Union() or Concat() methods. The reason is that these methods cannot handle duplicate keys properly.

For instance, consider the following dictionaries with a duplicate key:

var testKey = "TEST";
var testValueLeft = "1";
var testValueRight = "2";
var left = new Dictionary<string, string>()
{
    [testKey] = testValueLeft
};
var right = new Dictionary<string, string>()
{
    [testKey] = testValueRight
};

var merged = left.Union(right).ToDictionary(t => t.Key, t => t.Value);

This will throw an exception:

System.ArgumentException: An item with the same key has already been added.

In contrast, the MergeInPlace() method I’ve outlined here simply retains the value from the left dictionary when there is a key conflict.