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 &
For arrays you can use:
Array.FindIndex
int keyIndex = Array.FindIndex(words, w => w.IsKey);
For lists you can use List
int keyIndex = words.FindIndex(w => w.IsKey);
You can also write a generic extension method that works for any Enumerable
///Finds the index of the first item matching an expression in an enumerable.
///The enumerable to search.
///The expression to test the items against.
///The index of the first matching item, or -1 if no items match.
public static int FindIndex(this IEnumerable items, Func 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;