Create a the HashSet with specified equality comparer in CSharp

Description

The following code shows how to create a the HashSet with specified equality comparer.

Example


/* ww w .  j  ava  2 s .  c om*/
using System;
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");
        allVehicles.Add("B");
        
        foreach(string s in allVehicles){
           Console.WriteLine(s);
        }
        
    }
}

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();
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Collections »




ArrayList
BitArray
Collection
Comparer
HashSet
Hashtable
LinkedList
List
ListDictionary
OrderedDictionary
Queue
SortedList
SortedSet
Stack
StringCollection
StringDictionary