Sabari M Sabari M
Updated date Mar 13, 2023
We will learn how to convert an array to a HashSet using C# in this blog

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

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 15+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!