tags:

views:

323

answers:

3

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;
    }
}
+5  A: 

Try this...

var key = words.Where(x => x.IsKey == true);
Chalkey
+1  A: 

If you want to find the word you can use

var word = words.Where(item => item.IsKey).First();

This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()

To get both the item and the index you can use

KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();
Grizzly
linq is insane. I thought Java generics were crazy. Anyways, thanks for all the help.
initialZero
Is casting the return value accepted practice or is there a way to define the type of word?
initialZero
ok, I came up with this. DecodedMessageWord keyWord = words.Where(x => x.IsKey == true).First<DecodedMessageWord>();
initialZero
A: 
int keyIndex = words.ToList().FindIndex(w => w.IsKey);

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

masenkablast