Dictionary Key Case Sensitivity in C#

by Bradley 8. May 2009 16:26

By default you must make sure that a key used to look up a value in a dictionary matches the case of key used to store the value in a dictionary. Simply put, list["A"] would not return the same value as list["a"]. It would be safe to assume that the default behavior was selected for efficiency. After all would you want your code slowed down by doing list["a".ToUpper()], if you knew that the key used to look up a dictionary value would never have a different case than what was used to store it. With that in mind, if case were an issue, most of us would change our code to perform the ToUpper just described. Although this approach is functionally sound, your code could become unnecessarily cluttered. An equally functional approach that would keep your code uncluttered would be to use one of the alternate constructors for your dictionary, see example below.

using System.Collections.Generic;

Dictionary<string, string> list = 
    new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
list.Add("A", "Value");

if (list["A"] != null)
{
    Console.WriteLine("A can be A");
}

if (list["a"] != null)
{
    Console.WriteLine("a can also be A");
}

Tags: , ,

.NET | C#

Comments

7/8/2010 8:51:59 AM #

Immigrants from the European Union coming to Sweden can check the Union's information "Dialogue with citizens" to settle or study in another EU-country

visia info

7/9/2010 6:36:50 PM #

I really think that you've done a good job with this website it looks really good and you have a ton of great information as well, I know I found what I was searching for anyway. Just thought I would take the time to comment, again keep up the good work

May Levy

Add comment




biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Original Theme by Mads Kristensen | Modified by Crafty Coders