This post will discuss how to convert a List to HashSet in C# and vice versa.

Convert List to HashSet:

1. Using HashSet Constructor

We can use the HashSet constructor, which takes an IEnumerable<T> to construct a new instance of the HashSet<T> class containing distinct elements of the list.

Note that since HashSet contains distinct elements, it’ll discard any repeated elements in the list.

Download  Run Code

2. Enumerable.ToHashSet() method (System.Linq)

We can use ToHashSet() method to create a HashSet<T> from an IEnumerable<T>.

Download  Run Code

Convert HashSet to List:

1. Using List Constructor

We can use the List constructor, which takes an IEnumerable<T> to construct a new instance of the List<T> containing all elements of the set.

Download  Run Code

2. Enumerable.ToList() method (System.Linq)

We can use ToList() method to create a List<T> from an IEnumerable<T>.

Download  Run Code

That’s all about conversion between List and HashSet in C#.