ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

FirstIndex() and LastIndex()

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

Source

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

Author: Fons Sonnemans

Submitted on: 9 jun. 2011

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 6132