Find index of a value in an array

C#ArraysLinq

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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;

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

Try this...

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

Solution 6 - C#

Just posted my implementation of IndexWhere() extension method (with unit tests):

http://snipplr.com/view/53625/linq-index-of-item--indexwhere/

Example usage:

int index = myList.IndexWhere(item => item.Something == someOtherThing);

Solution 7 - C#

This solution helped me more, from msdn microsoft:

var result =  query.AsEnumerable().Select((x, index) =>
              new { index,x.Id,x.FirstName});

query is your toList() query.

Solution 8 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioninitialZeroView Question on Stackoverflow
Solution 1 - C#sidney.andrewsView Answer on Stackoverflow
Solution 2 - C#Paolo MorettiView Answer on Stackoverflow
Solution 3 - C#Jonas BötelView Answer on Stackoverflow
Solution 4 - C#GrizzlyView Answer on Stackoverflow
Solution 5 - C#user110714View Answer on Stackoverflow
Solution 6 - C#joelsandView Answer on Stackoverflow
Solution 7 - C#Roshna OmerView Answer on Stackoverflow
Solution 8 - C#Marcel Valdez OrozcoView Answer on Stackoverflow