How to merge two dictionaries in C#
In C#, a dictionary is a collection of key-value pairs, similar to a map or hash table in other programming languages. The key is used to look up the corresponding value in the dictionary. The dictionary in C# is implemented as a generic class called Dictionary<TKey, TValue>, where TKey is the data type of the key, and TValue is the value's data type.
We'll now look at how to merge two dictionaries in C#.
Using the Add() method
One way to merge two dictionaries in C# is by using the Add() method. We can use the Add() method to add the key-value pairs from one dictionary to another.
using System;using System.Collections.Generic;class Test{static void Main(string[] args){var dict1 = new Dictionary<string, int> {{ "A", 1 },{ "B", 2 }};var dict2 = new Dictionary<string, int> {{ "C", 3 },{ "D", 4 }};foreach (var kvp in dict2) {if (!dict1.ContainsKey(kvp.Key)) {dict1.Add(kvp.Key, kvp.Value);}}foreach (var kvp in dict1) {Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);}}}
Explanation
Let's take a look at the explanation for the code:
Lines 8–11: We create our first dictionary,
dict1, containing key-value pairs of typestringandint.Lines 13–16: We create our second dictionary,
dict2, containing key-value pairs of typestringandint.Lines 18–22: We use a
foreachloop to iterate overdict2and use theContainsKey()method to check if the key already exists indict1. If the key does not exist indict1, we use theAdd()method to add the key-value pair todict1.Lines 24–26: We use a
foreachloop to iterate overdict1and display its key-value pairs.
Note: In the code above, we ignore a key-value pair if the key already exists in
dict1and avoid any overwriting.
Using the Concat() method
Another way to merge two dictionaries in C# is by using the Concat() method. This method is available in the System.Linq namespace. Here's an example:
using System;using System.Collections.Generic;using System.Linq;class Test{static void Main(string[] args){var dict1 = new Dictionary<string, int> {{ "A", 1 },{ "B", 2 }};var dict2 = new Dictionary<string, int> {{ "C", 3 },{ "D", 4 }};var mergedDict = dict1.Concat(dict2).ToDictionary(x => x.Key, x => x.Value);foreach (var kvp in mergedDict) {Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);}}}
Explanation
Lines 9–12: We create our first dictionary,
dict1, containing key-value pairs of typestringandint.Lines 14–17: We create our second dictionary,
dict2, containing key-value pairs of typestringandint.Line 19: We use the
Concat()method to merge two dictionaries,dict1anddict2. Then, we use theToDictionary()method to convert the result to a dictionary.Lines 21–23: We use a
foreachloop to display the key-value pairs from the merged dictionary,mergedDict.
Free Resources