How to create a union of a HashSet with a collection in C#
The HashSet<T> generic class in the System.Collections.Generic namespace provides the UnionWith() method, which modifies the HashSet<T> such that it contains a union of current HashSet<T> and the specified collection provided as the input.
Syntax
public void UnionWith (System.Collections.Generic.IEnumerable<T> other);
- This method takes a
CollectionIEnumerable<T>as input and changes the currentHashSet<T>object to have all elements that are present in theHashSet<T>, the input collection, or both.
Things to note
-
This method represents the mathematical set union operation.
-
It is an operation, where n is the count of elements in the passed collection of elements.
-
It throws an exception if the input collection is
null. -
This method changes the state of the
HashSet<T>.
Code
In the following example, we create a HashSet of integers and add a few numbers to it. We also create a List of integers that have a few elements common with the HashSet, and some elements which are not present in the HashSet.
We call the UnionWith() method with the list of integers as input. It does a set union operation and modifies the HashSet to contain the union of itself and the specified list of integers.
We also print the elements of the HashSet before and after the UnionWith() operation, along with the list contents.
using System;using System.Collections.Generic;class HashSetUnion{static void Main(){HashSet<int> numSet = new HashSet<int>();numSet.Add(1);numSet.Add(5);numSet.Add(9);numSet.Add(11);numSet.Add(15);numSet.Add(6);Console.WriteLine("HashSet Elements : ");PrintSet(numSet);List<int> otherList = new List<int>{9,11,39};Console.WriteLine("Input List 1: {0}", string.Join(" ", otherList.ToArray()));numSet.UnionWith(otherList);Console.WriteLine("HashSet Elements after UnionWith() : ");PrintSet(numSet);}private static void PrintSet(HashSet<int> set){Console.Write("{");foreach (int i in set){Console.Write(" {0}", i);}Console.WriteLine(" }");}}