Dictionary
A case-insensitive Dictionary
is ideal in some programs. It helps with comparing file names in Windows, which ignore case.
Sometimes user names are case-insensitive—upper and lower letters are treated as equal. We implement a case-insensitive string
Dictionary
.
Suppose we want to add a string
"cat" to a Dictionary
. But we want to be able to look up "CAT" and "Cat" also. The insensitive Dictionary
is a solution.
cat -> cat, CAT, Cat
The Dictionary
class
has several overloaded constructors. Here we use one that accepts a generic IEqualityComparer
parameter.
IEqualityComparer
is an interface
. It is used by Dictionary
to acquire hash codes and compare keys.Dictionary
constructor that accepts an IEqualityComparer
. We specify StringComparer
OrdinalIgnoreCase
as the comparer.StringComparer
OrdinalIgnoreCase
implements (at minimum) 2 methods, Equals
and GetHashCode
.Dictionary
to compute hash keys and compare buckets.using System; using System.Collections.Generic; // Create case insensitive string Dictionary. var test = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); test.Add("Cat", 2); test.Add("Python", 4); test.Add("DOG", 6); // Write value of "cat". Console.WriteLine("{0} = {1}", test.GetValueOrDefault("cat"), test.GetValueOrDefault("CAT")); // Write value of "PYTHON". Console.WriteLine("{0} = {1}", test.GetValueOrDefault("PYTHON"), test.GetValueOrDefault("Python")); // See if "dog" exists. if (test.ContainsKey("dog")) { Console.WriteLine("Contains dog."); } // Enumerate all KeyValuePairs. foreach (var pair in test) { Console.WriteLine(pair); }2 = 2 4 = 4 Contains dog. [Cat, 2] [Python, 4] [DOG, 6]
You can add keys with either case using the Add method. The keys retain their original case internally in the Dictionary
buckets.
KeyValuePairs
(in foreach
), the original cases are retained.Dictionary
considers the 2 strings to be equivalent.ContainsKey
This method (along with TryGetValue
) will accept keys of either case. So "PYTHON" will return the same value as "Python".
ToLower
To normalize string
data in a Dictionary
, you can call ToLower
when adding or accessing keys. But this will cause additional allocations and more GC pressure.
We implemented a case-insensitive string
Dictionary
. You do not need a custom IEqualityComparer
, although if your requirements are slightly unusual this can help.