Case Sensitive Dictionary Keys

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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?

回答1:

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

Dictionary myDict = new Dictionary(); 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.



回答2:

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.



回答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.



转载请标明出处:Case Sensitive Dictionary Keys
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!