使用带字符串键的Hashtables/Dictionaries和Case Insensitive Searching

Eoi*_*ell 17 .net dictionary hashtable case-insensitive .net-3.5

想知道这是否可行.

我们有一个第三方库,其中包含有关用户的标识信息......

与库的主要交互是通过一个键控字符串的HashTable,并返回该键的信息的Object Graph.

问题是,关键显然是区分大小写,但我们从用户浏览器获得的内容并不一定与案例相符...(我们经常将密钥完全小写)

我想知道是否可以针对哈希表进行不敏感密钥搜索.

例如

Hashtable ht = new Hashtable();
ht.Add("MyKey", "Details");

string result = ht["MyKey"];
string result = ht["MYKEY"];
string result = ht["mykey"];
Run Code Online (Sandbox Code Playgroud)

如果有机会我们可以向公司提交支持票以添加此功能,是否有支持此功能的任何其他DataStructures(即新的通用集合/词典)

最后,是否有可能覆盖System.String GetHashCode()方法,使所有大小写不变的字符串返回相同的哈希码...例如,我认为这是一个没有人,因为string是密封的类

欢呼,如果有人有任何建议

Ras*_*dit 31

用于使哈希表比较不区分大小写的代码

适用于2.0,3.0,3.5

Hashtable ht = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
Run Code Online (Sandbox Code Playgroud)

您可以在 SO链接上获取有关InvariantCultureIgnoreCase与OrdinalIgnoreCase的信息

要么

Hashtable ht = System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
Run Code Online (Sandbox Code Playgroud)

由于不区分大小写的字典集合是如此常见的用法,因此.NET Framework具有一个CollectionUtil类,该类支持创建不区分大小写的Hashtable和SortedList对象.通过调用CreateCaseInsensitiveHashtable或CreateCaseInsensitiveSortedList来使用.

对于.Net 1.0(我不确定1.0是否支持StringComparer)

public class InsensitiveComparer : IEqualityComparer
{
    CaseInsensitiveComparer _comparer = new CaseInsensitiveComparer();
    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLowerInvariant().GetHashCode();
    }

    public new bool Equals(object x, object y)
    {
        if (_comparer.Compare(x, y) == 0)
        {
            return true;
        }

        else
       {
           return false;
       }
    }
}

Hashtable dehash = new Hashtable(new InsensitiveComparer());
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 17

用字典:

new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Run Code Online (Sandbox Code Playgroud)

但更简单,我相信StringDictionary也不区分大小写:

    StringDictionary ht = new StringDictionary();
    ht.Add("MyKey", "Details");

    string result1 = ht["MyKey"];
    string result2 = ht["MYKEY"];
    string result3 = ht["mykey"];
Run Code Online (Sandbox Code Playgroud)