How to Merge Dictionary in C# ?

Published on June 7, 2015 by abundantcode

Filed under C#

Last modified June 7, 2015

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 4071 times

There are times when you want to merge 2 dictionary collections to one . Below is a code sample that shows how to do it.

How to Merge Dictionary in C# ?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AbundantcodeConsoleApp
    class Program
        static void Main(string[] args)
            Dictionary<int, string> dictionary1 = new Dictionary<int, string>();
            dictionary1.Add(1, "item 1");
            dictionary1.Add(2, "item 2");
            Dictionary<int, string> dictionary2 = new Dictionary<int, string>();
            dictionary2.Add(1, "item 1");
            dictionary2.Add(4, "item 4");
            var result = dictionary1.Concat(dictionary2).GroupBy(d => d.Key)
              .ToDictionary(d => d.Key, d => d.First().Value);
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

1 Comment

  1. How to Convert Integer to Hex and Vice versa in C# ? | Abundant Code
    June 7, 2015 - 9:18 pm

Leave a Comment


You might be Interested in these Posts

How to Get the number of elements in ArrayList in C# ?

Here's the code that demonstrates how one can get the total number of elements contained in the Arra...

How to Check if the ArrayList is read-only in C# ?

There are times when you would use the read-only wrapper in order to prevent modifying the ArrayList...

Using HashSet to remove duplicates from array in C#

If you want to remove duplicates from an array in C# , one of the options is to use HashSet as shown...