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.
Asked
Active
Viewed 1.1k times
4 Answers
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
-
1I am stuck with .Net 2 sadly :( – Grzenio Oct 07 '09 at 10:48
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
-
-
@geo1701: but you **do need** `using System.Linq` to get the new overload with the `StringComparer` ! – marc_s Nov 21 '13 at 07:28
-
Thanks, good answer, I was hoping there was an extension, rather than having to write my own. Otherwise I would not have known where to look! – Abacus Feb 10 '14 at 23:16
-
However, that does not help one actually get to the item in the list.... – David V. Corbin Aug 03 '22 at 16:47
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