48684

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,
Answer1:
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);