How to Merge Two Dictionaries in C# Easily
Concat method combined with ToDictionary to create a new dictionary. Alternatively, you can use a foreach loop to add or update entries from one dictionary into another.Syntax
To merge two dictionaries, you can use LINQ's Concat method to combine key-value pairs and then convert them back to a dictionary with ToDictionary. This creates a new dictionary containing all entries.
Alternatively, use a foreach loop to add or update entries from the second dictionary into the first one.
var merged = dict1.Concat(dict2).ToDictionary(pair => pair.Key, pair => pair.Value); // Or update dict1 with dict2 entries foreach (var pair in dict2) { dict1[pair.Key] = pair.Value; // Adds or updates }
Example
This example shows how to merge two dictionaries into a new one using LINQ, and how to update the first dictionary with entries from the second.
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var dict1 = new Dictionary<string, int> { {"apple", 1}, {"banana", 2} }; var dict2 = new Dictionary<string, int> { {"banana", 3}, {"cherry", 4} }; // Merge into new dictionary var merged = dict1.Concat(dict2) .ToDictionary(pair => pair.Key, pair => pair.Value); Console.WriteLine("Merged dictionary:"); foreach (var item in merged) { Console.WriteLine($"{item.Key}: {item.Value}"); } // Update dict1 with dict2 entries foreach (var pair in dict2) { dict1[pair.Key] = pair.Value; } Console.WriteLine("\nUpdated dict1:"); foreach (var item in dict1) { Console.WriteLine($"{item.Key}: {item.Value}"); } } }
Common Pitfalls
When merging dictionaries, a common mistake is not handling duplicate keys, which causes an exception with ToDictionary. Using Concat blindly merges all pairs, so if keys repeat, you must decide which value to keep.
Another pitfall is modifying the original dictionary unintentionally when you want a new merged dictionary.
try { // This throws if duplicate keys exist var merged = dict1.Concat(dict2).ToDictionary(pair => pair.Key, pair => pair.Value); } catch (ArgumentException) { // Handle duplicates by choosing dict2's value var mergedSafe = dict1.Concat(dict2) .GroupBy(pair => pair.Key) .ToDictionary(g => g.Key, g => g.Last().Value); }
Quick Reference
- Concat + ToDictionary: Creates a new merged dictionary but throws on duplicate keys.
- GroupBy + ToDictionary: Handles duplicates by selecting which value to keep.
- foreach loop: Updates or adds entries directly to an existing dictionary.