Hashset

HashSet

HashSet is an unordered collection of elements and a generic collection type. The HashSet supports the implementation of sets and uses the hash table for storage. The HashSet is available in the System.Collections.Generic namespace.

  • It doesn’t allow duplicate values and can accept only one null value in the collection.

  • The HashSet class implements the IEnumerable and many other interfaces

  • The elements in a HashSet cannot be sorted because it is an unordered collection,

  • The HashSet increases dynamically as we add elements because the memory is allocated dynamically and doesn’t have any fixed size.

  • The HashSet also supports set operations like intersection, union, and difference, along with creating, inserting and removing the elements.

using System;
using System.Collections.Generic;

class Program
{
    public static void Main()
    {
        HashSet<string> hashset1 = new HashSet<string>();

        hashset1.Add("Banana");
        hashset1.Add("Mango");
        hashset1.Add("Apple");
        hashset1.Add("Banana");

        foreach (var value in hashset1)
            Console.WriteLine(value);

        hashset1.Remove("Mango");

        foreach (var value in hashset1)
            Console.WriteLine(value);
    }
}

Last updated