Created
August 21, 2014 19:54
-
-
Save paulpdaniels/3c2c043283b5a3f99d39 to your computer and use it in GitHub Desktop.
Linq fast indexOf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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