C# .NET Tips case insensitive dictionary
By default, dictionary keys in .NET are case-sensitive. However, if you want to make a dictionary case-insensitive, you can achieve this by using a case-insensitive comparer when you create the dictionary. Here’s a sample code snippet demonstrating how to do this using C#:
Dictionary<string, string> products
= new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "product1", "Mobile" },
{ "product2", "Laptop" },
{ "product3", "Desktop" },
};
Console.WriteLine($"Product1: {products["Product1"]}");
Output
In this example, we use StringComparer.OrdinalIgnoreCase
as the comparer when creating the dictionary. This comparer treats keys as case-insensitive, allowing you to access dictionary entries without being concerned about the case of the keys.