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);
set.Add("john");
Debug.Assert(set.Contains("JohN"));
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.
Edit
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…