How to use HashSet<string>.Contains() method in case -insensitive mode?

How to use HashSet<string>.Contains() method in case -insensitive mode?


You can create the HashSet with a custom comparer:

HashSet<string> hs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

hs.Add("Hello");

Console.WriteLine(hs.Contains("HeLLo"));

You need to create it with the right IEqualityComparer:

HashSet<string> hashset = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);

It's not necessary here, as other answers have demonstrated, but in other cases where you are not using a string, you can choose to implement an IEqualityComparer<T> and then you can use a .Contains overload. Here is an example using a string (again, other answers have shown that there is already a string comparer you can use that meets your needs). Many methods surrounding IEnumerable<T> have overloads that accept such comparers, so it's good to learn how to implement them.

class CustomStringComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return x.Equals(y, StringComparison.InvariantCultureIgnoreCase);
    }

    public int GetHashCode(string obj)
    {
        return obj.GetHashCode();
    }
}

And then use it

bool contains = hash.Contains("foo", new CustomStringComparer());

You should use the constructor which allows you to specify the IEqualityComparer you want to use.

HashSet<String> hashSet = new HashSet<String>(StringComparer.InvariantCultureIgnoreCase);

The StringComparer object provides some often used comparer as static properties.