This post will discuss how to convert an array to a HashSet<T> in C#.

1. Using HashSet<T> Constructor

The HashSet<T> class has a Constructor that takes an IEnumerable and initializes a new instance of the HashSet<T> class with elements of an array. The following example shows how to create a new HashSet<T> from an array.

Download  Run Code

 
The following code creates an extension method that generates a HashSet<T> from an IEnumerable<T> using its constructor:

Download  Run Code

2. Using ToHashSet() Method

C# provides a built-in method ToHashSet() starting with .Net Framework 4.7.2. It creates a HashSet<T> from any IEnumerable<T>, as shown below:

Download  Run Code

That’s all about converting an array to a HashSet<T> in C#.