FirstIndex() and LastIndex()

public static int FirstIndex<T>(this IEnumerable<T> list, Func<T, bool> predicate) {
    int index = 0;
    foreach (var item in list) {
        if (predicate(item)) {
            return index;
        }
        index++;
    }
    return -1;
}

public static int LastIndex<T>(this IEnumerable<T> list, Func<T, bool> predicate) {
    int index = 0;
    foreach (var item in list.Reverse()) {
        if (predicate(item)) {
            return list.Count() - index - 1;
        }
        index++;
    }
    return -1;
}
Example:
int[] l = new int[] { 3, 2, 1, 2, 6 };

Console.WriteLine(l.FirstIndex(n => n == 2)); // 1
Console.WriteLine(l.LastIndex(n => n == 2));  // 3

Description

Finds the index of the first of last occurence which matches the predicate.

Details

Double click on the code to select all.

 

;