wishmaster wishmaster - 1 year ago 241
C# Question

Make HashSet<string> case-insensitive

I have method with HashSet parameter. And I need to do case-insensitive Contains within it:

public void DoSomething(HashSet<string> set, string item)
var x = set.Contains(item);

Is it any way to make existing HashSet case-insensitive (do not create new one)?

I'm looking for solution with best perfomance.


Contains can be called multiple times. So IEnumerable extensions are not acceptable for me due to lower perfomance than native HashSet Contains method.


Since, answer to my question is NO, it is impossible, I've created and used following method:

public HashSet<string> EnsureCaseInsensitive(HashSet<string> set)
return set.Comparer == StringComparer.OrdinalIgnoreCase
? set
: new HashSet<string>(set, StringComparer.OrdinalIgnoreCase);

Answer Source

The HashSet<T> constructor has an overload that lets you pass in a custom IEqualityComparer<string>. There are a few of these defined for you already in the static StringComparer class, a few of which ignore case. For example:

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

You'll have to make this change at the time of constructing the HashSet<T>. Once one exists, you can't change the IEqualityComparer<T> it's using.

Just so you know, by default (if you don't pass in any IEqualityComparer<T> to the HashSet<T> constructor), it uses EqualityComparer<T>.Default instead.


The question appears to have changed after I posted my answer. If you have to do a case insensitive search in an existing case sensitive HashSet<string>, you will have to do a linear search:

set.Any(s => string.Equals(s, item, StringComparison.OrdinalIgnoreCase));

There's no way around this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download