Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive string for use in dictionary?

Tags:

c#

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,

like image 495
JoeS Avatar asked Nov 20 '25 16:11

JoeS


1 Answers

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);
like image 129
Sriram Sakthivel Avatar answered Nov 23 '25 05:11

Sriram Sakthivel