2012-12-07 26 views
7

Istnieje List<T>.FindIndex(Int32, Predicate <T>). Ta metoda jest dokładnie tym, co chcę dla obiektu IList<T>.
Wiem, że IList ma metodę IndexOf(T), ale potrzebuję predykatu do zdefiniowania algorytmu porównywania.IList <T> .FindIndex (Int32, Predicate <T>)

Czy istnieje metoda, metoda rozszerzenia, LINQ lub jakiś kod w celu znalezienia indeksu elementu w numerze IList<T>?

+0

Myślałem, istnieją pewne LINQ wzywa, aby to zrobić. Ale jeśli połączę np. 'Gdzie (...)' z czymś innym indeks jest tracony. – thersch

Odpowiedz

13

Cóż można naprawdę łatwo napisać własną metodę rozszerzenia:

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; 
} 
Powiązane problemy