UnionWith Method in C#


Use the UnionWith method in C# to get the union of i.e. unique lements from two collections.

Let’s say the following are our Dictionary −

Dictionary < string, int > dict1 = new Dictionary < string, int > ();
dict1.Add("pencil", 1);
dict1.Add("pen", 2);
Dictionary < string, int > dict2 = new Dictionary < string, int > ();
dict2.Add("pen", 3);

Now, use HashSet and UnionWith to get the union −

HashSet < string > hSet = new HashSet < string > (dict1.Keys);
hSet.UnionWith(dict2.Keys);

The following is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {
      Dictionary < string, int > dict1 = new Dictionary < string, int > ();
      dict1.Add("pencil", 1);
      dict1.Add("pen", 2);

      Dictionary < string, int > dict2 = new Dictionary < string, int > ();
      dict2.Add("pen", 3);

      HashSet < string > hSet = new HashSet <string > (dict1.Keys);
      hSet.UnionWith(dict2.Keys);

      Console.WriteLine("Merged Dictionary...");
      foreach(string val in hSet) {
         Console.WriteLine(val);
      }
   }
}

Output

Merged Dictionary...
pencil
pen

Updated on: 22-Jun-2020

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements