Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of a value in an array

Tags:

arrays

c#

linq

People also ask

How do you find the index of an element?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

What is the index of an array?

The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.


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


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;
        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;

int keyIndex = words.TakeWhile(w => !w.IsKey).Count();

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();

Try this...

var key = words.Where(x => x.IsKey == true);