4

I have a list that holds a few strings(names). For this example. It will hold:

  • TeSt1
  • TeSt2
  • TeSt3

And I'm trying to check if that list has one of those. And I'm doing this like this at the moment:

if (list.Contains(test2))
{

}

But I need it to be case insensitive.. But how can I do that? in an if statement.

Stian Tofte
  • 213
  • 6
  • 13
  • See [this other answer](http://stackoverflow.com/questions/3107765/how-to-ignore-the-case-sensitivity-in-liststring). Use `StringComparison.OrdinalIgnoreCase`. – Gigi May 03 '14 at 17:51
  • For simple, non-accented strings, such as the english language, simple append what Gigi suggests: `list.Contains("test2", StringComparer.OrdinalIgnoreCase)` – mdisibio May 03 '14 at 18:03

3 Answers3

5

The Contains method has an overload that accepts an IEqualityComparer. You can give it one by doing the following:

 if (list.Contains(test2, StringComparer.OrdinalIgnoreCase))  
 {  
     // do something  
 }
carpenter
  • 1,192
  • 1
  • 14
  • 25
1

IndexOf has a parameter for case insensitive search

culture.CompareInfo.IndexOf(toSearch, word, CompareOptions.IgnoreCase) 

where culture is the instance of CultureInfo describing the language that the text is written in.

You can loop through the list and see if it each list entry matches the search.

zszep
  • 4,450
  • 4
  • 38
  • 58
  • `CompareInfo.IndexOf` doesn't take a list, it searches for a substring within another string. –  May 03 '14 at 17:53
  • @hvd. I know. I made my answer clearer by stating that you have loop through the list to compare – zszep May 03 '14 at 18:07
  • But you shouldn't be checking for substrings at all, only for complete matches. –  May 03 '14 at 18:23
-2

Make your list lower case......and

if (list.Contains(test2.ToLower()))
{

}
HackerMan
  • 904
  • 7
  • 11