简体   繁体   English

使用C#在区分大小写的字典中不区分大小写地搜索

[英]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. 我不想使用foreach遍历此字典并比较每个值,因为字典包含太多数据。

Is there a better (most-efficient) way to to do this using C#? 有没有更好的(最有效的)方法来使用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? 因此,如果我对它的理解正确,那么您需要一个字典,该字典按原样保存字符串,但是以不区分大小写的方式散列,这样无论大小写,您仍然可以在O(1)摊销时间内进行搜索?

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). 我看到它的方式,你需要通过一个自定义IEqualityComparer创建时Dictionary此构造和实施时IEqualityComparer治疗字符串,就好像它们是例如全部大写或小写和相同的散列码(即返回的哈希码的字符串变为大写)。

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"). 现在,实际上您的字典通常可以正常保存字符串,但是在搜索或添加时,它们会将它们视为大写,因此将“ AbcD”与“ aBCd”(都称为“ 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). 都铎王朝的答案是一个很好的答案,我想建议您使用StringComparer.CurrentCultureIgnoreCase而不是创建自己的比较器类(特别是如果预期结果相同)来补充它。

Example : 范例:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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