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.
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:
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