Find index of a value in an array

initialZero picture initialZero · Nov 19, 2009 · Viewed 142.5k times · Source

Can linq somehow be used to find the index of a value in an array?

For instance, this loop locates the key index within an array.

for (int i = 0; i < words.Length; i++)
{
    if (words[i].IsKey)
    {
        keyIndex = i;
    }
}

Answer

sidney.andrews picture sidney.andrews · Nov 20, 2009
int keyIndex = Array.FindIndex(words, w => w.IsKey);

That actually gets you the integer index and not the object, regardless of what custom class you have created