C# HashSet<T>

C# HashSet class can be used to store, remove or view elements. It does not store duplicate elements. It is suggested to use HashSet class if you have to store only unique elements. It is found in System.Collections.Generic namespace.

C# HashSet<T> example

Let's see an example of generic HashSet<T> class that stores elements using Add() method and iterates elements using for-each loop.

snippet
using System;
using System.Collections.Generic;

public class HashSetExample
{
    public static void Main(string[] args)
    {
        // Create a set of strings
        var names = new HashSet();
        names.Add("Sonoo");
        names.Add("Ankit");
        names.Add("Peter");
        names.Add("Irfan");
        names.Add("Ankit");//will not be added
        
        // Iterate HashSet elements using foreach loop
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

Output:

Output
Sonoo Ankit Peter Irfan

C# HashSet<T> example 2

Let's see another example of generic HashSet<T> class that stores elements using Collection initializer.

snippet
using System;
using System.Collections.Generic;

public class HashSetExample
{
    public static void Main(string[] args)
    {
        // Create a set of strings
        var names = new HashSet(){"Sonoo", "Ankit", "Peter", "Irfan"};
        
        // Iterate HashSet elements using foreach loop
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

Output:

Output
Sonoo Ankit Peter Irfan
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents