HashSet creation

In this chapter you will learn:

  1. How to create HashSet from Comparer

Create HashSet

The code below creates a new instance of the HashSet<T> class that uses the specified equality comparer.

using System;//from j  av  a2  s  . c  o m
using System.Collections.Generic;

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

        allVehicles.Add("A");
        allVehicles.Add("T");
        allVehicles.Add("B");
    }
}

class MyComparer : EqualityComparer<string>
{
    public override bool Equals(string s1, string s2)
    {
        return s1.Equals(s2, StringComparison.CurrentCultureIgnoreCase);
    }
    public override int GetHashCode(string s)
    {
        return base.GetHashCode();
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Remove a single element from HashSet
  2. How to remove all elements from HashSet
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