This post will discuss how to add the contents of a Dictionary to another Dictionary in C#. The solution should add key-value pairs present in the given dictionary into the source dictionary.

1. Using List<T>.ForEach() method

The idea is to convert the second dictionary into a List of KeyValuePair<K,V> Then, insert each entry into the first dictionary using the ForEach() method.

Download  Run Code

 
The above code throws an ArgumentException when attempting to add a duplicate key.

To overwrite 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  Run Code

2. Using foreach loop

We can also iterate over the dictionary using a regular foreach loop and append all the second dictionary entries into the first dictionary. This solution handles duplicate keys as it uses the dict[key] property instead of the Add() method.

Download  Run Code

That’s all about adding contents of a Dictionary to another Dictionary in C#.