merge two dictionaries using concat in csharp

In C#, you can use the Concat() method from LINQ to merge two dictionaries. Here's an example:

main.cs
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> dict1 = new Dictionary<string, int> {{"apple", 1}, {"banana", 2}};
        Dictionary<string, int> dict2 = new Dictionary<string, int> {{"cherry", 3}, {"orange", 4}};

        var mergedDict = dict1.Concat(dict2);

        foreach (var item in mergedDict)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }
    }
}
514 chars
20 lines

In the above code, we have two dictionaries dict1 and dict2. We use the Concat() method from LINQ to concatenate both dictionaries. The resulting mergedDict is an IEnumerable<KeyValuePair<string, int>>. We can iterate over mergedDict using a foreach loop and print the key-value pairs.

Output:

main.cs
Key: apple, Value: 1
Key: banana, Value: 2
Key: cherry, Value: 3
Key: orange, Value: 4
87 chars
5 lines

related categories

gistlibby LogSnag