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!


About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.