Creating Case Insensitive Dictionaries In .NET

For millennia, mankind has looked to the stars and wondered, “How can I create a generic Dictionary in .NET that allows me use case insensitive strings as keys?” Well today that age old question will be answered with this neat trick.

Simply put, all you need to do is add a StringComparer object when constructing a generic Dictionary that uses a string key, and make sure to use on of the IgnoreCase StringComparers that are offered. Below is some sample code to illustrate just how easy this is.

// Create a generic dictionary with a string comparer that ignores case sensitivity.
// This includes the following:
//  - CurrentCultureIgnoreCase
//  - InvariantCultureIgnoreCase
//  - OrdinalIgnoreCase
Dictionary<string, string> stringMap = 
     new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
stringMap.Add("Test Key", "Some value");

// Now try to access or change the corresponding value with the key.
// The case of the key string no longer matters.
stringMap["test key"] = "This will work";
stringMap["TEST KEY"] = "And also this";
stringMap["tEsT kEy"] = "And this as well";
stringMap["tEST kEY"] = "And finally this";

// This can be done with any dictionary that uses a string as the key
Dictionary<string, int> numberMap = 
     new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
numberMap.Add("Test Key", 0);

// Same deal here, you can use any case to get or set the values in the map
numberMap["test key"] = 1;
numberMap["TEST KEY"] = 2;
numberMap["tEsT kEy"] = 3;
numberMap["tEST kEY"] = 4;

And that’s all there is to it.  I hope you enjoy and find this useful.

Richard Franzen
ImageSource, Inc.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s