Multiple string comparison with C#

Use Enumerable.Contains<T> which is an extension method on IEnumerable<T>:

var strings = new List<string> { "A", "B", "C" };
string x = // some string
bool contains = strings.Contains(x, StringComparer.OrdinalIgnoreCase);
if(contains) {
    // do something
}

if ((new[]{"A","B","C"}).Contains(x, StringComparer.OrdinalIgnoreCase))

Why yes, there's a classic thread here on StackOverflow with an extension method that would do exactly what you're looking for.

A Use For Extension Methods

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}

EDIT in response to comment below: If you are only solely concerned with strings then:

public static bool In(this string source, params string[] list)
{
    if (null == source) throw new ArgumentNullException("source");
    return list.Contains(source, StringComparer.OrdinalIgnoreCase);
}

Which leads to the syntax you're familiar with:

if(x.In("A","B","C"))
{
  // do something....
}

Note, this is pretty much exactly the same as everyone else has posted only in a syntax closest to what you mentioned.

Tags:

C#

String