10

I've found plenty of info on the web about making dictionaries able to do case insensitive look-ups such that if I added a key/value pair of ("A", "value") calling

MyDict["a"] == MyDict["A"]

will return true.

What I want to know is why I get a "key has already been added" error when I do

MyDict.Add("A", "value1");
MyDict.Add("a", "value2");

if I defined my dictionary to do case sensitive look-ups. Is there no way to define a Dictionary to be able to add different cased keys?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
spots
  • 2,483
  • 5
  • 23
  • 38

3 Answers3

15

Dictionaries are case-sensitive by default - you don't need to do anything.

Dictionary<string, string> myDict = new Dictionary<string, string>();
myDict.Add("A", "value1");
myDict.Add("a", "value2");

See your code working online here: ideone.

If you are getting an error with your code then it's because one of those keys already exist in your dictionary.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    It did already exist (means I need coffee), unfortunately I have to manually create a large dictionary with a ton of values and didn't account for the possibility of duplicates coming in. Thank you, also I've never seen ideone before so thank you for that too. – spots Dec 21 '12 at 18:42
11

All Dictionaries are case-sensisitive. But you can use the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

Check it from ideone.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
3

The OP is actually correct if he was using the StringDictionary Class. Microsoft's site states that the key is converted to lower-case before it's stored (https://msdn.microsoft.com/en-us/library/system.collections.specialized.stringdictionary(v=vs.110).aspx). To make the key case sensitive, using the Generic Dictionary as Mark Byers suggested works nicely. If you want a case insensitive key, StringDictionary works well.

Paurian
  • 1,372
  • 10
  • 18
  • 1
    I seem to be running into this. if I have a Dictionary does it automatically make it a StringDictionary and just doesn't make it obvious for me? – Joshua K Dec 24 '18 at 17:35