Site icon Ryadel

Case-Insensitive Dictionary in ASP.NET C#

Classe ASP.NET C# per il controllo e il calcolo formale del Codice Fiscale

When working in ASP.NET, we often make use of the powerful Dictionary class, which is one of the most awesome ways - although not always the most efficient one - to handle key-value pairs of (almost) any sort. When using a String object as key, we often want it to be case-sensitive, so we can store different items in the following way:

And so on. This is nothing less than the Dictionary class default behavior: if we stick to the above example we'll have three different entries, each one accessible with their specific, case-sensitive string.

This might or might not be convenient, depending on our specific scenario. Whenever we need the key to be case-insensitive, we can do that by adding a StringComparer to the constructor method in the following way:

The above dictionary will have one single entry, which we can get by using its case-insensitive key.

We should be also aware of the fact that, as stated in this StackOverflow thread, using StringComparer.OrdinalIgnoreCase will give you better performance than using StringComparer.InvariantCultureIgnoreCase, assuming we simply need to disregard the case of characters.

That's about it: happy coding!

 

Exit mobile version