C# – Case insensitive dictionary

If you want a case insensitive dictionary, use:

new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase);
Code language: C# (cs)

In the Dictionary constructor you can specify how keys are compared. For string keys, the default is a case sensitive comparison. To make it case insensitive, you can pass in StringComparer.InvariantCultureIgnoreCase.


I have a table that maps users to devices. The user-to-device mapping gets cached in memory using a Dictionary<string, int>.

When the user makes a request, it goes to their mapped device. It uses their name as a key however they typed it in when they logged in. Because of the potential mismatch between what’s in the database and how the user is logging in, we decided to use a case insensitive dictionary.

var computerIdMap = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase) { { "Bob", 1 }, { "alice", 2 } };
Code language: C# (cs)

Now when Alice logs in, she can use “alice” or “Alice” or any other variation, and it’ll all map to { “alice”, 2 }.

Leave a Comment