This post will discuss how to merge two or more dictionaries in C#. The solution should append key-value pairs present in all dictionaries into a new dictionary.

1. Using LINQ

We can use LINQ to merge any number of dictionaries in C#. The following code example shows how to implement this.

Download Code

 
If any of the keys gets repeated in any dictionary, the above code throws an ArgumentException. To handle this, the idea is to group elements based on the key before converting it to a dictionary.

Download Code

 
We can also use the ToLookup() method to get multiple values per key, as shown below:

Download Code

2. Using Dictionary.Add() method

Here, the idea is to create a new dictionary, iterate over each dictionary, and manually add each pair to the new dictionary. This is demonstrated below:

Download Code

 
The above code throws an ArgumentException, when attempting to add a duplicate key. To update the value of a key already present in the Dictionary, we can use dict[key] = value syntax instead of the Add() method. This is demonstrated below:

Download Code

3. Using Union() method

Alternatively, we can use the Union() method to facilitate the merge of dictionaries into one another.

Download Code

 
The above code throws an ArgumentException if it reencounters the same key. To handle the duplicate keys, the idea remains the same – group elements based on the key before converting to a dictionary.

Download Code

That’s all about merging dictionaries in C#.

 
Also See:

Add contents of a Dictionary to another Dictionary in C#