To merge two dictionaries in C#, you can use the `Union` method from the `System.Linq` namespace or iterate through one dictionary and add its elements to the other dictionary using the `Add` method. This allows you to combine the key-value pairs from both dictionaries.
We can merge two dictionaries in C# using the `Union` method from the `System.Linq` namespace. This example demonstrates how to declare and initialize two dictionaries, use the `Union` method to merge them, and print the merged dictionary.
For example,
using System.Collections.Generic;
and using System.Linq;
.firstDict
and secondDict
with integer keys and string values.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize two dictionaries
Dictionary<int, string> firstDict = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"}
};
Dictionary<int, string> secondDict = new Dictionary<int, string>
{
{3, "Three"},
{4, "Four"}
};
// Merge the dictionaries using Union
Dictionary<int, string> mergedDict = firstDict
.Union(secondDict)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// Print the merged dictionary
Console.WriteLine("Merged dictionary:");
foreach (var kvp in mergedDict)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Merged dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three Key: 4, Value: Four
We can merge two dictionaries in C# by iterating through one dictionary and adding its elements to the other dictionary using the `Add` method. This example demonstrates how to declare and initialize two dictionaries, iterate through the second dictionary to add its elements to the first dictionary, and print the merged dictionary.
For example,
using System.Collections.Generic;
.firstDict
and secondDict
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize two dictionaries
Dictionary<int, string> firstDict = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"}
};
Dictionary<int, string> secondDict = new Dictionary<int, string>
{
{3, "Three"},
{4, "Four"}
};
// Merge the dictionaries by adding elements from secondDict to firstDict
foreach (var kvp in secondDict)
{
firstDict.Add(kvp.Key, kvp.Value);
}
// Print the merged dictionary
Console.WriteLine("Merged dictionary:");
foreach (var kvp in firstDict)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Merged dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three Key: 4, Value: Four
In this tutorial, we learned How to Merge Two Dictionaries in C# language with well detailed examples.