Use A Prefab Comparer For Case-Insensitive Dictionaries

by Jon Davis 22. September 2009 14:56

I'm kicking myself because I always just assumed that generic dictionaries in C#, i.e. Dictionary<string, object>, were case-sensitive. I always assumed that in order to have a case-insensitive dictionary, you had to do one of two things:

  1. public class CaseInsensitiveDictionary<TValue> : Dictionary<string, TValue> { ... }
  2. var item = myDictionary.Find(kvp=>kvp.Key.ToLower() == myKey.ToLower());

Actually, Dictionary<K,V> has a constructor that accepts a comparer object with which you can take advantage of prefab case-insensitive key-matching behavior.

Dictionary<string,object> myDictionary = new Dictionary<string,object>(StringComparer.InvariantCultureIgnoreCase);

I realized this upon stumbling across the MSDN documentation, which, of course, everyone reads for fun. 

http://msdn.microsoft.com/en-us/library/ms132073.aspx

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading




 

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

Jon Davis (aka "stimpy77") has been a programmer, developer, and consultant for web and Windows software solutions professionally since 1997, with experience ranging from OS and hardware support to DHTML programming to IIS/ASP web apps to Java network programming to Visual Basic applications to C# desktop apps.
 
Software in all forms is also his sole hobby, whether playing PC games or tinkering with programming them. "I was playing Defender on the Commodore 64," he reminisces, "when I decided at the age of 12 or so that I want to be a computer programmer when I grow up."

Jon was previously employed as a senior .NET developer at a very well-known Internet services company whom you're more likely than not to have directly done business with. However, this blog and all of jondavis.net have no affiliation with, and are not representative of, his former employer in any way.

Contact Me 


Tag cloud

Calendar

<<  October 2020  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar