This post will discuss how to merge two HashSets in C#.

1. Using HashSet<T>.UnionWith() Method

The shortest and most idiomatic way to merge contents of a HashSet<T> object with contents of another HashSet<T> is using the HashSet<T>.UnionWith() method. It modifies the HashSet<T> to contain all elements that are present in itself along with elements in the specified HashSet (or any other IEnumerable in general). It can be used to add multiple values to an existing HashSet<T> object, as shown below:

For example, the following code merges all the elements contained in the second set with the elements contained in the first set. Note that a set permits no duplicate elements.

Download  Run Code

2. Using foreach loop

Alternatively, you can iterate over the second set using a foreach loop and add each element to the first set. The following code example demonstrates this:

Download  Run Code

That’s all about merging two HashSets in C#.