简体   繁体   中英

Searching case insensitively in case sensitive dictionary using c#

I have a case sensitive dictionary (very huge one). I want to search the keys of this dictionary using ignore-case (case-insensitive). I don't want to use foreach to iterate throughout this dictionary and compare each values as the dictionary contains too many data.

Is there a better (most-efficient) way to to do this using C#? I want some suggestions.

So if I understand it correctly you want a dictionary that holds strings as they are, but hashes in a case-insensitive manner, such that you can still search in O(1) amortized time regardless of case?

The way I see it you need to pass a custom IEqualityComparer when creating the Dictionary with this constructor and when implementing the IEqualityComparer treat strings as if they are all upper or lower case for example and the same for the hash code (ie return the hash code of the string turned to upper case).

For example:

class MyComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return x.ToUpper() == y.ToUpper();
    }

    public int GetHashCode(string obj)
    {
        return obj.ToUpper().GetHashCode();
    }
}

...

Dictionary<String, String> dict = new Dictionary<string, string>(new MyComparer());

Now practically your dictionary holds the strings normally but when searching or adding it treats them as if they are all uppercase so "AbcD" is treated the same as "aBCd" (both as "ABCD").

Tudor's answers was a good one and I'd like to complement it by recommanding you to use the StringComparer.CurrentCultureIgnoreCase instead of creating your own comparer class (especialy if the expected result is the same).

Example :

Dictionary<string, string> openWith = 
                  new Dictionary<string, string>( 
                      StringComparer.CurrentCultureIgnoreCase);

Source : http://msdn.microsoft.com/en-us/library/ms132072.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM