HashSet

In this chapter you will learn:

  1. How to use HashSet
  2. A set of integer

Use HashSet

HashSet<T> is implemented with a hashtable that stores just keys. SortedSet<T> is implemented with a red/black tree. The following constructs a HashSet<char> from an existing collection, tests for membership, and then enumerates the collection.

using System;//j  a  v  a2  s.com
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Sample
{
    public static void Main()
    {
        var letters = new HashSet<char>("java2s.com tutorial and demo");

        Console.WriteLine(letters.Contains('t')); // true
        Console.WriteLine(letters.Contains('j')); // false

        foreach (char c in letters) 
            Console.Write (c);
    }

}

The output:

We can pass a string into HashSet<char>'s constructor because string implements IEnumerable<char>.

A set of integers

The following code creates two sets. One is for odd numbers and other is for even numbers.

using System;/*jav  a  2 s  .  co m*/
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> evenNumbers = new HashSet<int>();
        HashSet<int> oddNumbers = new HashSet<int>();

        for (int i = 0; i < 5; i++)
        {
            evenNumbers.Add(i * 2);
            oddNumbers.Add((i * 2) + 1);
        }

        Console.Write(evenNumbers.Count);
        DisplaySet(evenNumbers);

        Console.Write(oddNumbers.Count);
        DisplaySet(oddNumbers);
        HashSet<int> numbers = new HashSet<int>(evenNumbers);
        numbers.UnionWith(oddNumbers);
        Console.Write(numbers.Count);
        DisplaySet(numbers);
    }
    private static void DisplaySet(HashSet<int> set)
    {
        foreach (int i in set)
        {
            Console.WriteLine(" {0}", i);
        }
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to do Set operation Except
  2. Set opertation SymmetricExceptWith
Home » C# Tutorial » Collections
HashSet
Set operation: Except
Set operator intersect
Remove with condition
HashSet contains
HashSet creation
HashSet removing element
Sub set operations
Hashtable
Hashtable ContainsValue
Add elements to a Hashtable
Hashtable containsKey
Remove from Hashtable
Hashtable to array
Queue
Generic Queue
Stack