TechieClues TechieClues
Updated date Mar 13, 2023
We will learn how to convert an array to a HashSet using C# in this blog
  • 1.8k
  • 0
  • 0

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

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

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