Skip to content

Instantly share code, notes, and snippets.

@paulpdaniels
Created August 21, 2014 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulpdaniels/3c2c043283b5a3f99d39 to your computer and use it in GitHub Desktop.
Save paulpdaniels/3c2c043283b5a3f99d39 to your computer and use it in GitHub Desktop.
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