How to check if string exists in a List<string>

If you need to determine whether or not a string exists within a List<string>, you may want to ignore the case of the strings while doing the compare.

Thanks to an extension method that hangs off of the List<T>.Contains() method, this is very easy to do.

Say you have a List<string> which contains email addresses and you want to check to see if a specific email address exists within the List<string>, your code may look like this:

List<string> emails = new List<string>() {“keean@domain.com”, “ty@domain.com”, “milo@domain.com” };

string target = “KEEAN@domain.com”;

if (emails.Contains(target, StringComparer.OrdinalIgnoreCase))

    Console.WriteLine(“{0} exists in the list.”, target);

else

    Console.WriteLine(“{0} does not exist in the list.”, target);

For more information on the StringComparer class, read this MS article.

If you use the StringComparer class, you will notice that there are three “IgnoreCase” properties:

  1. StringComparer.CurrentCultureIgnoreCase
  2. StringComparer.InvariantCultureIgnoreCase
  3. StringComparer.OrdinalIgnoreCase

These are enumerations that specifies the culture, case, and sort rules to be used by certain overloads of the String.Compare and String.Equals methods. For more information, check out this article.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s