Dictionary
Consider a VB.NET Dictionary
that has String
keys—the key "Cat" is different than the key "cat." This makes sense, as the characters are different.
But sometimes we want case-insensitive lookups, where uppercase and lowercase are the same. We can specify StringComparer
OrdinalIgnoreCase
to achieve this effect.
This VB.NET program creates a Dictionary
specifies a custom IEqualityComparer
in its constructor. It demonstrates the use of case-insensitivity in Dictionary
keys.
Dictionary
with String
keys. We specify StringComparer
OrdinalIgnoreCase
to determine how keys are hashed and checked.Dictionary
. The keys are case-insensitive, but the original keys added are stored exactly.GetValueOrDefault
to test "cat" and "CAT", and we determine that the returned values are equal.For-Each
loop, we print out all the original keys and values. We can see that the original cases are still present in the keys.Module Module1 Sub Main() ' Step 1: create Dictionary specifying OrdinalIgnoreCase. Dim test = New Dictionary(Of String, Integer)(StringComparer.OrdinalIgnoreCase) ' Step 2: add some case-insensitive string keys. test.Add("Cat", 2) test.Add("Python", 4) test.Add("DOG", 6) ' Step 3: test one key with different cases. Dim result1 = test.GetValueOrDefault("cat") Dim result2 = test.GetValueOrDefault("CAT") Console.WriteLine($" Cat: {result1} = {result2}") ' Step 4: test another key. Dim result3 = test.GetValueOrDefault("PYTHON") Dim result4 = test.GetValueOrDefault("Python") Console.WriteLine($"Python: {result3} = {result4}") ' Step 5: print out all entries in the Dictionary. For Each pair in test Console.WriteLine(pair) Next End Sub End Module Cat: 2 = 2 Python: 4 = 4 [Cat, 2] [Python, 4] [DOG, 6]
IEqualityComparer
When we specify the StringComparer
, we are changing the IEqualityComparer
of the Dictionary
. This will affect how many functions, like TryGetValue
and ContainsKey
, work.
Dictionary
functions will automatically become case-insensitive when we specify OrdinalIgnoreCase
.Given that Windows uses case-insensitive file names, using a case-insensitive Dictionary
is often helpful. Many VB.NET programs can benefit from StringComparer
OrdinalIgnoreCase
.