Is string in array?

Solution 1:

Just use the already built-in Contains() method:

using System.Linq;

//...

string[] array = { "foo", "bar" };
if (array.Contains("foo")) {
    //...
}

Solution 2:

I know this is old, but I wanted the new readers to know that there is a new method to do this using generics and extension methods.

You can read my blog post to see more information about how to do this, but the main idea is this:

By adding this extension method to your code:

public static bool IsIn<T>(this T source, params T[] values)
{
    return values.Contains(source);
}

you can perform your search like this:

string myStr = "str3"; 
bool found = myStr.IsIn("str1", "str2", "str3", "str4");

It works on any type (as long as you create a good equals method). Any value type for sure.

Solution 3:

You're simply after the Array.Exists function (or the Contains extension method if you're using .NET 3.5, which is slightly more convenient).