IEqualityComparer
This C# interface
requires Equals
and GetHashCode
methods. It can be used to implement fuzzy key matching—this can lead to cleaner code as strings can be looked up directly.
Though IEqualityComparer
can be used to add hashing functionality for any object, we focus on strings. We use it with the Dictionary
type. Existing code that uses Dictionary
can be left unchanged.
A Dictionary
by default uses exact lookups. It computes a hash code based on a key and if another value matches it exactly, the two keys match. But this can be changed.
IEqualityComparer
.GetHashCode
) and compares keys (in Equals
) ignoring all hyphen characters.string
"cat-1" is considered equal to the string
"cat1." The hyphen (dash) character is simply ignored.Main
method shows how hyphens are ignored in the keys of a Dictionary
that uses this comparer.using System; using System.Collections.Generic; class CustomComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { int xPos = 0; int yPos = 0; while (true) { // ... Fail if past end. if (xPos >= x.Length) { return false; } if (yPos >= y.Length) { return false; } // ... Skip past hyphens. if (x[xPos] == '-') { xPos++; continue; } if (y[yPos] == '-') { yPos++; continue; } // ... Fail if different. if (x[xPos] != y[yPos]) { return false; } // ... If we have traversed both strings with no error, we match. if (xPos == x.Length - 1 && yPos == y.Length - 1) { return true; } // ... Increment both places. xPos++; yPos++; } } public int GetHashCode(string obj) { int code = 0; // ... Add together all chars. for (int i = 0; i < obj.Length; i++) { if (obj[i] != '-') { code += obj[i]; } } return code; } } class Program { static void Main() { // ... Add data to dictionary. var dictionary = new Dictionary<string, int>(new CustomComparer()); dictionary["cat-1"] = 1; dictionary["cat-2"] = 2; dictionary["dog-bark"] = 10; dictionary["dog-woof"] = 20; // ... Lookup values, ignoring hyphens. Console.WriteLine(dictionary["cat1"]); Console.WriteLine(dictionary["cat-1"]); Console.WriteLine(dictionary["dog--bark"]); } }1 1 10
Probably the best reason to use IEqualityComparer
is when we went to treat different keys as though they are equal. In the example, we ignore hyphens in keys, so they can be omitted.
string
keys. We can just look up existing keys rather than creating new strings.IEqualityComparer
is a helpful interface
for this reason.With IEqualityComparer
, we look up strings based on the results of a method. We can apply fuzzy matching, or any other transformation before comparing keys.