C# – Case insensitive dictionary

Dictionaries with string keys are case sensitive by default. If you want a case-insensitive dictionary, use the Dictionary constructor that takes a string comparison option and pass in StringComparer.InvariantCultureIgnoreCase, like this:

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

Note: There are other case-insensitive options you can pick from, such as OrdinalIgnoreCase.

Example

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.

Here’s an example of declaring this case insensitive dictionary and initializing with values:

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

Because this is case insensitive, you can get the value from the dictionary by using any variation of the key (such as “alice”, “Alice”, etc…).

Leave a Comment