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 type string and int.

  • Lines 13–16: We create our second dictionary, dict2, containing key-value pairs of type string and int.

  • Lines 18–22: We use a foreach loop to iterate over dict2 and use the ContainsKey() method to check if the key already exists in dict1. If the key does not exist in dict1, we use the Add() method to add the key-value pair to dict1.

  • Lines 24–26: We use a foreach loop to iterate over dict1 and display its key-value pairs.

Note: In the code above, we ignore a key-value pair if the key already exists in dict1 and 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 type string and int.

  • Lines 14–17: We create our second dictionary, dict2, containing key-value pairs of type string and int.

  • Line 19: We use the Concat() method to merge two dictionaries, dict1 and dict2. Then, we use the ToDictionary() method to convert the result to a dictionary.

  • Lines 21–23: We use a foreach loop to display the key-value pairs from the merged dictionary, mergedDict.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved