C#: List.Contains Method – Case Insensitive


I had a list of strings and needed to check whether or not a specific string was contained within the list ignoring the character casing.  Pre-LINQ days you would have had to loop through the entries calling the .ToLower or ToUpper method on each of the elements or using the string.Compare method.  But thanks to LINQ, one simple method will take care of this for us:

List<string> list = new List<string>() { "a", "b", "c", "d", "e" };
string value = "A";

if (list.Contains(value, StringComparer.OrdinalIgnoreCase))
    Console.WriteLine(value + " is in the list!");
else
    Console.WriteLine(value + " is not in the list!");

6 Responses to “C#: List.Contains Method – Case Insensitive”

  1. Dave Graper Says:

    Quick and to the point … thanks!

  2. RivkA Says:

    Tnanks very much – that is what I was looking for 🙂

  3. Steve Chambers Says:

    Probably obvious to most but worth pointing out that you need the “using System.Linq;” directive to use this extension method.

  4. marwa Says:

    This solution does not take care of space in your string

  5. Manisha Says:

    Thanks buddy!

  6. wert Says:

    This is what was looking for. Many thanks


Leave a reply to Steve Chambers Cancel reply