Tasawer Khan
Tasawer Khan

Reputation: 6148

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

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

Upvotes: 72

Views: 43248

Answers (4)

Kobi
Kobi

Reputation: 138017

You need to create it with the right IEqualityComparer:

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

Upvotes: 10

Anthony Pegram
Anthony Pegram

Reputation: 126854

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

Upvotes: 6

Thibault Falise
Thibault Falise

Reputation: 5885

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.

Upvotes: 5

Jo&#227;o Angelo
Jo&#227;o Angelo

Reputation: 57688

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"));

Upvotes: 124

Related Questions