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.

2
  • See this other answer. Use StringComparison.OrdinalIgnoreCase. Commented May 3, 2014 at 17:51
  • For simple, non-accented strings, such as the english language, simple append what Gigi suggests: list.Contains("test2", StringComparer.OrdinalIgnoreCase) Commented May 3, 2014 at 18:03

3 Answers 3

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  
 }
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

CompareInfo.IndexOf doesn't take a list, it searches for a substring within another string.
@hvd. I know. I made my answer clearer by stating that you have loop through the list to compare
But you shouldn't be checking for substrings at all, only for complete matches.
-2

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

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

}

3 Comments

Thats bad, why would he want to make his list lower case?
Data alteration to check a condition? Sounds good enough.
Will fail in culture specific comparison cases, see Turkey Test

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.