简体   繁体   中英

Case insensitive string for use in dictionary?

I need a dictionary to have a key that is a string but ignores case. I've decompiled the Dictionary type and it basically creates a hash table of the key's hash code. I can't subclass string because its a primitive type so I've created my own class to use as a key:

struct StringCaseInsensitiveHash
{
    private readonly string _innerString;
    public StringCaseInsensitiveHash(string str)
    {
        _innerString = str;
    }

    public static implicit operator string(StringCaseInsensitiveHash stringCaseInsensitiveHash)
    {
        return stringCaseInsensitiveHash._innerString;
    }

    public override int GetHashCode()
    {
        return _innerString.ToLower().GetHashCode();
    }
}

Is there a better way to do this though?

Thanks,

Dictionary constructor allows you to pass IEqualityComparer which it will use to compare the keys and for hashing purpose too.

You can use StringComparer.OrdinalIgnoreCase , StringComparer.CurrentCultureIgnoreCase or StringComparer.InvariantCultureIgnoreCase depends upon your need.

More info available in MSDN

var myDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

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