Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A case-insensitive list

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.

like image 243
Grzenio Avatar asked Oct 07 '09 10:10

Grzenio


2 Answers

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.

like image 120
Jon Skeet Avatar answered Nov 09 '22 14:11

Jon Skeet


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
}
like image 23
CestLaGalere Avatar answered Nov 09 '22 15:11

CestLaGalere