views:

265

answers:

3

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.

+4  A: 

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.

Jon Skeet
I am stuck with .Net 2 sadly :(
Grzenio
+2  A: 

Similar story here where looking to check for contains

e.g.

public static bool Contains(this string source, string toCheck, StringComparison comp)
        {
            return source.IndexOf(toCheck, comp) >= 0;
        }
dove
+1  A: 

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;
    }
}
Grzenio