Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
781 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...