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!");
    Console.WriteLine(value + " is not in the list!");

4 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: