Hi,
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.
Hi,
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.
Looks like its possible to leverage the KeyedCollection class:
public class Set<T> : KeyedCollection<T,T>
{
public Set()
{}
public Set(IEqualityComparer<T> comparer) : base(comparer)
{}
public Set(IEnumerable<T> collection)
{
foreach (T elem in collection)
{
Add(elem);
}
}
protected override T GetKeyForItem(T item)
{
return item;
}
}