Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Sensitive Dictionary Keys

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?

like image 551
spots Avatar asked Dec 21 '12 18:12

spots


People also ask

Is dictionary keys are case-sensitive?

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

Is Dictionary Containskey case-sensitive C#?

The default constructor of C# Dictionary class constructs a Dictionary object, in which the keys are case sensitive. So when you insert data pairs <Key, Value> and <key, Value>, they are regarded as two different items.

Is Python get case-sensitive?

YES, Python is a case-sensitive programming language. This means that it treats uppercase and lowercase letters differently.

What is case-sensitive C#?

In computers, case sensitivity defines whether uppercase and lowercase letters are treated as distinct (case-sensitive) or equivalent (case-insensitive).


2 Answers

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.

like image 120
Paurian Avatar answered Sep 30 '22 22:09

Paurian


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.

like image 34
Soner Gönül Avatar answered Sep 30 '22 22:09

Soner Gönül