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.

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