What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , trackbacks - 0

QuickTip: Case Insensitive Dictionaries

I've often thought about making my own implementation of a Dictionary<K,V> where the key values are case insensitive.

Its been one of those things on my ever-growing to-do list. I usually end up casting the key values to all uppercase and try to encapsulate all my calls the the dictionary with my own logic that performs the case conversion.  A case insensitive dictionary would avoid all that nastiness.

Sometimes it's helpful to read the tooltip overloads. As I coded a new dictionary instance today, I stumbled upon the

Dictionary<(Of <(TKey, TValue>)>) Constructor (IEqualityComparer<(Of <(TKey>)>)) overload.  

Apparently I can pass my own equality comparer into the constructor which tells the dictionary how to compare key values.   Could it really be that easy?

Yep, it exactly that easy.  To make my dictionary<string,string> use case insensitive keys, declare the dictionary as follows:

Dictionary<string, string> argList = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);

Now  args["Test"] and args["TEST"] return the same item from my dictionary.

I love it when I can mark things done on my to-do list without actually having to do any work.

Print | posted on Wednesday, April 30, 2008 3:28 PM | Filed Under [ Visual Studio ]



# re: QuickTip: Case Insensitive Dictionaries

Fantastic tip! Just what I was looking for
8/3/2009 9:27 PM | ilyas

# re: QuickTip: Case Insensitive Dictionaries

very nice
8/30/2011 4:44 AM | Mitchell & Ness Baltimore Oriole

# re: QuickTip: Case Insensitive Dictionaries

it did not work with any of the StringComparer alternatives :(
7/7/2017 9:04 AM | Manish

# re: QuickTip: Case Insensitive Dictionaries

@manish - it works with every comparer I've tried. Do you have specific examples of it not working? I'd love to test them out.
11/29/2017 4:21 PM | Chris D
Post A Comment

Powered by: