This blog will teach you how to convert an array to a HashSet<T> in C#. We can use the below methods to achieve the result.
- Using
ToHashSet()
Method - Using
HashSet<T>
Using ToHashSet()
Method
HashSet<T>
method is an inbuilt C# method starting from the .Net framework 4.7.2. It easily converts an array to a HashSet as shown below,
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConvertArrayToHashSet
{
class Program
{
static void Main()
{
string[] colors = { "Red", "Green", "Blue", "Yellow", "White" };
HashSet<string> hashSet = colors.ToHashSet();
Console.WriteLine(String.Join(", ", hashSet));
Console.ReadKey();
}
}
}
Output:
Red, Green, Blue, Yellow, White
Using HashSet<T>
The HashSet<T>
class provides a constructor which is used to convert an array to a HashSet. The below example explains how to create a new HashSet<T>
from an array.
using System;
using System.Collections.Generic;
namespace ConvertArrayToHashSet
{
class Program
{
static void Main()
{
string[] colors = { "Red", "Green", "Blue", "Yellow", "White" };
HashSet<string> hashSet = new HashSet<string>(colors);
Console.WriteLine(String.Join(", ", hashSet));
Console.ReadKey();
}
}
}
Output:
Red, Green, Blue, Yellow, White
Comments (0)