Dictionary Case-Insensitive
This page was last reviewed on Jan 10, 2024.
Dot Net Perls
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 1 We create a Dictionary with String keys. We specify StringComparer OrdinalIgnoreCase to determine how keys are hashed and checked.
Step 2 We add 3 keys and their associated values to our Dictionary. The keys are case-insensitive, but the original keys added are stored exactly.
Step 3 We use GetValueOrDefault to test "cat" and "CAT", and we determine that the returned values are equal.
Dictionary GetValueOrDefault
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 10, 2024 (new).
© 2007-2024 Sam Allen.