Case, 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.
Example. This VB.NET program creates a Dictionary specifies a custom IEqualityComparer in its constructor. It demonstrates the use of case-insensitivity in Dictionary keys.
Step 4 We also test "PYTHON" and "Python" and both of these access the value stored for the original key "Python".
Step 5 With a 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.
And All the Dictionary functions will automatically become case-insensitive when we specify OrdinalIgnoreCase.
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.