How to combine 2 dictionaries into a third dictionary in C#

3 Answers

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var dict1 = new Dictionary<int, string> {
            {1, "aaa"},
            {2, "bbb"}
        };

        var dict2 = new Dictionary<int, string>
        {
            {3, "ccc"},
            {4, "ddd"},
            {2, "XYZ"}
        };

        var combined = new Dictionary<int, string>(dict1);

        foreach (var kvp in dict2) {
            combined[kvp.Key] = kvp.Value; // Overwrites if key already exists
        }

        foreach (var kvp in combined) {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}



/*
run:

1: aaa
2: XYZ
3: ccc
4: ddd

*/

 



answered Aug 25 by avibootz
0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var dict1 = new Dictionary<int, string> {
            {1, "aaa"},
            {2, "bbb"}
        };

        var dict2 = new Dictionary<int, string>
        {
            {3, "ccc"},
            {4, "ddd"},
            {2, "XYZ"}
        };

        var combined = new Dictionary<int, string>(dict1);

        foreach (var kvp in dict2) {
            if (combined.ContainsKey(kvp.Key))
                combined[kvp.Key] += ", " + kvp.Value; // merge values
            else
                combined[kvp.Key] = kvp.Value;
        }

        foreach (var kvp in combined) {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}



/*
run:

1: aaa
2: bbb, XYZ
3: ccc
4: ddd

*/

 



answered Aug 25 by avibootz
0 votes
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var dict1 = new Dictionary<int, string> {
            {1, "aaa"},
            {2, "bbb"}
        };

        var dict2 = new Dictionary<int, string> {
            {3, "ccc"},
            {4, "ddd"},
            {2, "XYZ"}
        };

        var combined = dict1.Concat(dict2)
                            .GroupBy(kvp => kvp.Key)
                            .ToDictionary(g => g.Key, g => g.Last().Value); // dict2 wins

        foreach (var kvp in combined) {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}




/*
run:

1: aaa
2: XYZ
3: ccc
4: ddd

*/

 



answered Aug 25 by avibootz
...