I need a case insensitive list or set type of collection (of strings). What is the easiest way to create one? You can specify the type of comparison you want to get on the keys of a Dictionary, but I can't find anything similar for a List.
Assuming you're using .NET 3.5, you can just use:
var strings = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
... or something similar, where you'd pick the appropriate culture setting as well.
A list doesn't really have the idea of a comparison for the most part - only when you call IndexOf
and related methods. I don't believe there's any way of specifying the comparison to use for that. You could use List<T>.Find
with a predicate, however.
Use Linq, this adds a new method to .Compare
using System.Linq;
using System.Collections.Generic;
List<string> MyList = new List<string>();
MyList.Add(...)
if (MyList.Contains(TestString, StringComparer.CurrentCultureIgnoreCase)) {
//found
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With