Coder Perfect

Checking to see if a string array includes a value and, if yes, locating it

Problem

This string array is what I’ve got:

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

I’m trying to figure out if stringArray has any value. If that’s the case, I’d like to know where it belongs in the array.

I’m not a fan of loops. Can somebody give me some ideas on how I could go about doing this?

Asked by MoShe

Solution #1

You might be able to make use of the Array. method indexOf:

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
}

Answered by Darin Dimitrov

Solution #2

var index = Array.FindIndex(stringArray, x => x == value)

Answered by BLUEPIXY

Solution #3

Exists: is another option.

string[] array = { "cat", "dog", "perl" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perl");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

Answered by Taran

Solution #4

EDIT: I hadn’t realized you were also in need of the position. Because IndexOf is implemented explicitly, you can’t use it on an array value directly. You can, however, use:

IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
    ...
}

(It’s the same as calling Array.) IndexOf is an alternative approach to Darin’s response. I’m not sure why IListT> exists. IndexOf is explicitly implemented in arrays, but that’s beside the point…)

Answered by Jon Skeet

Solution #5

You can make use of Array. Note that if the element cannot be found, IndexOf() will return -1, and you must handle this circumstance.

int index = Array.IndexOf(stringArray, value);

Answered by BrokenGlass

Post is based on https://stackoverflow.com/questions/7867377/checking-if-a-string-array-contains-a-value-and-if-so-getting-its-position