Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Linq fast indexOf
namespace System.Linq {
public static class EnumerableExtensions {
public static int IndexOf<T1>(this IEnumerable source, Func<T1, bool> predicate) {
var enumerator = source.GetEnumerator();
bool lastEval = false;
int index = -1;
while (enumerator.MoveNext() && !(lastEval = predicate(enumerator.Current))) {
++index;
}
//If the last evaluation is still false we broke the loop without finding anything
return lastEval ? index : -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment