This post will discuss how to add elements of a List<T> to a HashSet<T> in C#.

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

The HashSet<T>.UnionWith() method modifies the HashSet by merging all its elements with the specified collection. The following example demonstrates the usage of the UnionWith() method by adding elements of a List<T> to an existing HashSet<T>:

Download  Run Code

2. Using foreach loop

Alternatively, you can create an extension method that act as AddRange() equivalent for a HashSet<T>. It adds elements of the specified collection to a HashSet<T> using a foreach loop. Note that a Set data structure doesn’t permit duplicates and maintains no particular order of its elements.

Download  Run Code

3. Using Enumerable.Concat() Method

Both above solutions add all elements of the List<T> to the HashSet<T>. You can use LINQ’s Enumerable.Concat() method to create a new collection containing elements of both the source set and the given list.

Download  Run Code

That’s all about adding elements of a List<T> to a HashSet<T> in C#.