C# program to merge two Dictionaries

Merging dictionaries in C# involves combining two or more Dictionary objects into one. This can be useful when you need to consolidate data from different sources or combine configuration settings.

There are several approaches to merge dictionaries, each with different behaviors for handling duplicate keys.

Syntax

Following is the syntax for creating dictionaries −

Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();

Following is the syntax for adding elements −

dict.Add(key, value);
dict[key] = value; // overwrites if key exists

Using HashSet to Merge Keys Only

This approach merges only the keys from both dictionaries, ignoring duplicate values. It uses HashSet with the UnionWith() method −

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Dictionary<string, int> dict1 = new Dictionary<string, int>();
        dict1.Add("laptop", 1);
        dict1.Add("desktop", 2);

        Dictionary<string, int> dict2 = new Dictionary<string, int>();
        dict2.Add("desktop", 3);
        dict2.Add("tablet", 4);
        dict2.Add("mobile", 5);

        HashSet<string> hSet = new HashSet<string>(dict1.Keys);
        hSet.UnionWith(dict2.Keys);
        
        Console.WriteLine("Merged Keys:");
        foreach(string val in hSet) {
            Console.WriteLine(val);
        }
    }
}

The output of the above code is −

Merged Keys:
laptop
desktop
tablet
mobile

Using LINQ Union Method

You can merge dictionaries using LINQ's Union() method. This approach handles duplicate keys by keeping the first occurrence −

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static void Main() {
        Dictionary<string, int> dict1 = new Dictionary<string, int>();
        dict1.Add("laptop", 1);
        dict1.Add("desktop", 2);

        Dictionary<string, int> dict2 = new Dictionary<string, int>();
        dict2.Add("desktop", 3);
        dict2.Add("tablet", 4);

        var merged = dict1.Union(dict2.Where(x => !dict1.ContainsKey(x.Key)))
                          .ToDictionary(x => x.Key, x => x.Value);

        Console.WriteLine("Merged Dictionary:");
        foreach(var item in merged) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

The output of the above code is −

Merged Dictionary:
laptop: 1
desktop: 2
tablet: 4

Using Loop to Merge with Overwrite

This approach iterates through the second dictionary and adds or overwrites values in the first dictionary −

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Dictionary<string, int> dict1 = new Dictionary<string, int>();
        dict1.Add("laptop", 1);
        dict1.Add("desktop", 2);

        Dictionary<string, int> dict2 = new Dictionary<string, int>();
        dict2.Add("desktop", 3);
        dict2.Add("tablet", 4);
        dict2.Add("mobile", 5);

        // Merge dict2 into dict1, overwriting duplicates
        foreach(var item in dict2) {
            dict1[item.Key] = item.Value;
        }

        Console.WriteLine("Merged Dictionary (with overwrite):");
        foreach(var item in dict1) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

The output of the above code is −

Merged Dictionary (with overwrite):
laptop: 1
desktop: 3
tablet: 4
mobile: 5

Comparison of Methods

Method Duplicate Key Behavior Preserves Values
HashSet UnionWith Ignored (keys only) No
LINQ Union with Filter Keeps first occurrence Yes
Loop with Indexer Overwrites with second value Yes

Conclusion

Merging dictionaries in C# can be accomplished using different methods depending on your needs. Use HashSet for key-only merging, LINQ for preserving original values, or loop iteration for overwriting duplicate keys with new values.

Updated on: 2026-03-17T07:04:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements