C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
IEqualityComparer: This object implements an interface and is used by Dictionary to acquire hash codes and compare keys.
IEqualityComparerNew: We use a Dictionary constructor that accepts an IEqualityComparer. We specify StringComparer.OrdinalIgnoreCase as the comparer.
Methods: StringComparer.OrdinalIgnoreCase implements (at minimum) 2 methods, Equals and GetHashCode.
StringComparison, StringComparerInfo: These 2 methods are used internally by the Dictionary to compute hash keys and compare buckets.
C# program that uses case-insensitive Dictionary
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create case insensitive string Dictionary.
var caseInsensitiveDictionary = new Dictionary<string, int>(
StringComparer.OrdinalIgnoreCase);
caseInsensitiveDictionary.Add("Cat", 2);
caseInsensitiveDictionary.Add("Python", 4);
caseInsensitiveDictionary.Add("DOG", 6);
// Write value of "cat".
Console.WriteLine(caseInsensitiveDictionary["CAT"]); // 2
// Write value of "PYTHON".
Console.WriteLine(caseInsensitiveDictionary["PYTHON"]); // 4
// See if "dog" exists.
if (caseInsensitiveDictionary.ContainsKey("dog"))
{
Console.WriteLine("Contains dog."); // <-- Displayed
}
// Enumerate all KeyValuePairs.
foreach (var pair in caseInsensitiveDictionary)
{
Console.WriteLine(pair.ToString());
}
}
}
Output
2
4
Contains dog.
[Cat, 2]
[Python, 4]
[DOG, 6]
And: When you enumerate the KeyValuePairs (in foreach), the original cases are retained.
ForeachCaution: When you add the strings "Cat" and "CAT", you will get an exception. The Dictionary considers the 2 strings to be equivalent.
File names: In Windows, file names are case-insensitive. But when users copy files, they expect them to retain their original case.
Thus: This Dictionary is ideal here. It will mimic the behavior of Windows NTFS filesystems.