Per gli array è possibile utilizzare: Array.FindIndex<T>
:
int keyIndex = Array.FindIndex(words, w => w.IsKey);
Per gli elenchi è possibile utilizzare List<T>.FindIndex
:
int keyIndex = words.FindIndex(w => w.IsKey);
È inoltre possibile scrivere un metodo di estensione generico che funziona per qualsiasi Enumerable<T>
:
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> 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;
}
Ed è possibile utilizzare LINQ così:
int keyIndex = words
.Select((v, i) => new {Word = v, Index = i})
.First(x => x.Word.IsKey).Index;
Si prega di notare che questo non sarà corto circuito il ciclo (itererà sempre sull'intera collezione) e genererà un'eccezione se la condizione non viene soddisfatta, piuttosto che restituire -1.
fonte
2012-11-29 16:41:15
In realtà, anche ottenere la parola andrebbe bene. – initialZero