merge two dictionaries in csharp

Here's one way to merge two dictionaries in C# using LINQ and KeyValuePair:

main.cs
Dictionary<string, int> dict1 = new Dictionary<string, int>()
{
    { "A", 1 },
    { "B", 2 }
};

Dictionary<string, int> dict2 = new Dictionary<string, int>()
{
    { "C", 3 },
    { "D", 4 }
};

Dictionary<string, int> mergedDict = dict1.Concat(dict2)
                                          .GroupBy(x => x.Key)
                                          .ToDictionary(x => x.Key, x => x.First().Value + x.Last().Value);
426 chars
16 lines

In this example, we have two dictionaries dict1 and dict2. We want to merge them into a single dictionary mergedDict such that the values for common keys are added up.

To achieve this, we first concatenate dict1 and dict2 using the Concat() method on dictionaries. Then we group the key-value pairs by key using the GroupBy() method. Finally, we use the ToDictionary() method to convert the grouped key-value pairs into a single dictionary, where we add up the values for each key using the First() and Last() methods of the IGrouping interface.

gistlibby LogSnag