Accepted answer
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


int index = -1;
index = words.any (word => { index++; return word.iskey; }) ? index : -1;


this solution helped me more, from msdn microsoft:

var result =  query.asenumerable().select((x, index) =>
              new { index,,x.firstname});

query is your tolist() query.


just posted my implementation of indexwhere() extension method (with unit tests):

example usage:

int index = mylist.indexwhere(item => item.something == someotherthing);


try this...

var key = words.where(x => x.iskey == true);


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 =, index) => new keyvaluepair<wordtype, int>(item, index)).where(item => item.key.iskey).first();


int keyindex = words.takewhile(w => !w.iskey).count();


for arrays you can use: array.findindex<t>:

int keyindex = array.findindex(words, w => w.iskey);

for lists you can use list<t>.findindex:

int keyindex = words.findindex(w => w.iskey);

you can also write a generic extension method that works for any enumerable<t>:

///<summary>finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">the enumerable to search.</param>
///<param name="predicate">the expression to test the items against.</param>
///<returns>the index of the first matching item, or -1 if no items match.</returns>
public static int findindex<t>(this ienumerable<t> items, func<t, bool> predicate) {
    if (items == null) throw new argumentnullexception("items");
    if (predicate == null) throw new argumentnullexception("predicate");

    int retval = 0;
    foreach (var item in items) {
        if (predicate(item)) return retval;
    return -1;

and you can use linq as well:

int keyindex = words
    .select((v, i) => new {word = v, index = i})
    .firstordefault(x => x.word.iskey)?.index ?? -1;

Related Query

More Query from same tag