IList<T>.FindIndex(Int32, Predicate <T>)
Asked Answered
S

1

16

There is a List<T>.FindIndex(Int32, Predicate <T>). That method is exactly what I want to for a IList<T> object.
I know IList has a method IndexOf(T) but I need the predicate to define the comparing algorithm.

Is there a method, extension method, LINQ or some code to find the index of an item in a IList<T>?

Shaeffer answered 7/12, 2012 at 16:51 Comment(1)
I thought there are some LINQ calls to do that. But if I combine e.g. Where(...) with something else the index is lost.Shaeffer
W
26

Well you can really easily write your own extension method:

public static int FindIndex<T>(this IList<T> source, int startIndex,
                               Predicate<T> match)
{
    // TODO: Validation
    for (int i = startIndex; i < source.Count; i++)
    {
        if (match(source[i]))
        {
            return i;
        }
    }
    return -1;
}
Wampum answered 7/12, 2012 at 16:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.