Convert an Array to a HashSet in C#
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { int[] numbers = { 1, 2, 3, 4, 2, 5 }; HashSet<int> set = new HashSet<int>(numbers); Console.WriteLine(String.Join(", ", set)); // 1, 2, 3, 4, 5 } } |
The following code creates an extension method that generates a HashSet<T>
from an IEnumerable<T>
using its constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; public static class Extensions { public static HashSet<T> ToHashSet<T>(this IEnumerable<T> collection) { return new HashSet<T>(collection); } } public class Example { public static void Main() { int[] numbers = { 1, 2, 3, 4, 2, 5 }; HashSet<int> set = numbers.ToHashSet(); Console.WriteLine(String.Join(", ", set)); // 1, 2, 3, 4, 5 } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { int[] numbers = { 1, 2, 3, 4, 2, 5 }; HashSet<int> set = numbers.ToHashSet(); Console.WriteLine(String.Join(", ", set)); // 1, 2, 3, 4, 5 } } |
That’s all about converting an array to a HashSet<T>
in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)