21

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.

dove
  • 20,469
  • 14
  • 82
  • 108
Grzenio
  • 35,875
  • 47
  • 158
  • 240

4 Answers4

33

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
23

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
}
CestLaGalere
  • 2,909
  • 1
  • 20
  • 20
3

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
  • 35,875
  • 47
  • 158
  • 240
2

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;
        }
Community
  • 1
  • 1
dove
  • 20,469
  • 14
  • 82
  • 108