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

C#StringHashset

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

You need to create it with the right IEqualityComparer:

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

Solution 3 - C#

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

Solution 4 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTasawer KhanView Question on Stackoverflow
Solution 1 - C#João AngeloView Answer on Stackoverflow
Solution 2 - C#KobiView Answer on Stackoverflow
Solution 3 - C#Anthony PegramView Answer on Stackoverflow
Solution 4 - C#Thibault FaliseView Answer on Stackoverflow