IEqualityComparer
When we create a Dictionary
with String
keys in VB.NET, we must have exact matches to find a key. This behavior can be changed with IEqualityComparer
.
With some logic in custom Equals
and GetHashCode
functions, we can ignore certain characters in keys. In this way, we can ignore all characters of a certain type, like digits, in keys.
Here we implement an IEqualityComparer
class
called CustomComparer
. We use the Implements and Shadows keywords to specify what functions are used in compilation.
Equals
, we loop through 2 equal-length strings, and compare all characters but ignore digits.GetHashCode
, we compute a hash code for all characters except digits. This allows us to completely ignore digits.Main
, we create a Dictionary
and specify the CustomComparer
, which is used within Dictionary
when computing hashing and testing keys.Dictionary
. All digit characters are considered equal.Class CustomComparer : Implements IEqualityComparer(Of String) Shadows Function Equals(x As String, y As String) As Boolean Implements IEqualityComparer(Of String).Equals ' Two strings are equal if they have all the same characters, and digits are always equal. If x.Length = y.Length For i = 0 To x.Length - 1 If Char.IsDigit(x(i)) And Char.IsDigit(y(i)) Continue For End If If x(i) <> y(i) Return False End If Next Return True End If Return False End Function Shadows Function GetHashCode(obj As String) As Integer Implements IEqualityComparer(Of String).GetHashCode ' Ignore digits when comparing a hash code. Dim result = 0 For i = 0 To obj.Length - 1 If Not Char.IsDigit(obj(i)) result += Asc(obj(i)) End If Next Return result End Function End Class Module Module1 Sub Main() ' Create a Dictionary with the IEqualityComparer. Dim test = New Dictionary(Of String, Integer)(New CustomComparer()) test.Add("bird123", 10) test.Add("cat3", 20) test.Add("dog", 30) ' Test the digit-ignoring comparer. Console.WriteLine(test.GetValueOrDefault("bird000")) Console.WriteLine(test.GetValueOrDefault("cat6")) Console.WriteLine(test.GetValueOrDefault("dog")) Console.WriteLine(test.GetValueOrDefault("bird5000")) End Sub End Module10 20 30 0
Suppose we have a Dictionary
that has keys but some parts of the keys are not important. By using a custom IEqualityComparer
, we can use the Dictionary
more directly.
Dictionary
lookups, which could improve performance.IEqualityComparer
—we could ignore punctuation, or character cases.While a String
Dictionary
requires exact key matches, with IEqualityComparer
we can modify this behavior. We can change Dictionary
to perform fuzzy string
matching.