๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# HashSet

A HashSet is a collection that stores each value at most once. Repeat additions are turned away.

Adding a value twice

The first Add stores the name and returns true. The second Add finds it present and returns false.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        HashSet<string> names = new HashSet<string>();
        Console.WriteLine(names.Add("Hana"));
        Console.WriteLine(names.Add("Hana"));
    }
}

Counting and checking members

Three distinct names enter the set, with one repeat. Count and Contains report the result.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        HashSet<string> names = new HashSet<string>();
        names.Add("Hana");
        names.Add("Ravi");
        names.Add("Mei");
        names.Add("Hana");
        Console.WriteLine(names.Count);
        Console.WriteLine(names.Contains("Ravi"));
        Console.WriteLine(names.Contains("Omar"));
    }
}

A sorted copy

The set itself has no print order. A copy in a list can be sorted and printed in order.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        HashSet<string> names = new HashSet<string>();
        names.Add("Ravi");
        names.Add("Hana");
        names.Add("Mei");
        List<string> copy = new List<string>(names);
        copy.Sort();
        foreach (string name in copy)
        {
            Console.WriteLine(name);
        }
    }
}

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        string[] words = { "cat", "dog", "cat", "bird", "dog" };
        HashSet<string> unique = new HashSet<string>();
        foreach (string word in words)
        {
            unique.Add(word);
        }
        Console.WriteLine(unique.Count);
        List<string> copy = new List<string>(unique);
        copy.Sort();
        foreach (string word in copy)
        {
            Console.WriteLine(word);
        }
    }
}

Key points

  • Add returns true when a value is new.
  • Add returns false when the value is already present.
  • Count reports the number of distinct values.
  • Contains answers membership without a search loop.
  • A set has no fixed print order.
  • A sorted copy gives a stable listing.

In this example, five words enter the set and the repeats drop away. Count prints 3. The sorted copy then prints bird, cat, and dog in alphabetical order.

Note

A HashSet suits questions of membership and uniqueness.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A HashSet holds 10, 20, and 30. What does Add(20) return?