C Sharp HashSet

C# HashSet<T>

To store, remove or view the elements, the HashSet<T> class is used in C# which is found in the System.Collections.Generic namespace. The C# HashSet<T> class can not store duplicate elements, and thus it is recommended to use for storing the unique elements only.

Example 1:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        // Create a set of strings  
        var countries = new HashSet<string>();  
        countries.Add("India");  
        countries.Add("Australia");  
        countries.Add("Japan");  
        countries.Add("Canada");  
        countries.Add("India");   
 
        // Iterate HashSet elements using foreach loop  
        foreach (var country in countries)  
        {  
            Console.WriteLine(country);  
        }  
    }  
}

Output:

Explanation:

In the above example, the generic HashSet<T> class is used. It uses the Add() method to store the elements and the for-each loop to iterate the list. Here, the duplicate element is not stored.

Example 2:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        // Create a set of strings  
        var countries = new HashSet<string>(){"India", "Australia", "Canada", "Mexico", "Japan"};  
 
        // Iterate HashSet elements using foreach loop  
        foreach (var country in countries)  
        {  
            Console.WriteLine(country);  
        }  
    }  
}

Output:

Explanation:

In the above example, the generic HashSet<T> class is used to store the elements using the Collection initializer.