views:

486

answers:

4

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

+7  A: 

You need to create it with the right IEqualityComparer:

HashSet<string> hashset = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
Kobi
+9  A: 

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"));
João Angelo
+1 Because you use `Ordinal` instead of `InvariantCulture`. The .NET guidelines advice us not to use `InvariantCulture` in most cases (see: http://msdn.microsoft.com/en-us/library/ms973919.aspx).
Steven
CurrentCultureIgnoreCase is usually the better choice.
Hans Passant
+4  A: 

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.

Thibault Falise
+2  A: 

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());
Anthony Pegram