How can I find the index of an item in a list without looping through it?
Currently this doesn\'t look very nice - searching through the list for the same item twice
Here's a copy/paste-able extension method for IEnumerable
public static class EnumerableExtensions
{
///
/// Searches for an element that matches the conditions defined by the specified predicate,
/// and returns the zero-based index of the first occurrence within the entire .
///
///
/// The list.
/// The predicate.
///
/// The zero-based index of the first occurrence of an element that matches the conditions defined by , if found; otherwise it'll throw.
///
public static int FindIndex(this IEnumerable list, Func predicate)
{
var idx = list.Select((value, index) => new {value, index}).Where(x => predicate(x.value)).Select(x => x.index).First();
return idx;
}
}
Enjoy.