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
385 views
in Technique[技术] by (71.8m points)

c# Dictionary: making the Key case-insensitive through declarations

I have a Dictionary<string, object> dictionary. It used to be Dictionary<Guid, object> but other 'identifiers' have come into play and the Keys are now handled as strings.

The issue is that the Guid keys from my source data are coming as VarChar, so now a key of "923D81A0-7B71-438d-8160-A524EA7EFA5E" is not the same as "923d81a0-7b71-438d-8160-a524ea7efa5e" (wasn't a problem when using Guids).

What's really nice (and sweet) about the .NET framework is that I can do this:

Dictionary<string, CustomClass> _recordSet = new Dictionary<string, CustomClass>(
    StringComparer.InvariantCultureIgnoreCase);

And that works great. But what about a nested Dictionary? Like the following:

Dictionary<int, Dictionary<string, CustomClass>> _customRecordSet 
    = new  Dictionary<int, Dictionary<string, CustomClass>>();

How would I specify the string comparer on a nested dictionary like this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When you add an element to the outer dictionary, you'll likely create a new instance of the nested dictionary, add it at this point, making use of the overloaded constructor that takes an IEqualityComparer<TKey>.

_customRecordSet.Add(0, new Dictionary<string, CustomClass>(StringComparer.InvariantCultureIgnoreCase));


Update 08/03/2017: Anecdotally, I read somewhere (I think in "Writing High-Performance .NET Code") that StringComparer.OrdinalIgnoreCase is more efficient when simply wanting to disregard the case of characters. This, however, is entirely unfounded by myself so YMMV.


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

...