Checking if a string array contains a value, and if so, getting its position

MoShe picture MoShe · Oct 23, 2011 · Viewed 396.6k times · Source

I have this string array:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

I would like to determine if stringArray contains value. If so, I want to locate its position in the array.

I don't want to use loops. Can anyone suggest how I might do this?

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 23, 2011

You could use the Array.IndexOf method:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
    // the array contains the string and the pos variable
    // will have its position in the array
}