You can write an iterator block extension method:
public static IEnumerable<T> SkipFirstMatching<T> (this IEnumerable<T> source, Func<T, bool> predicate) { if (source == null) throw new ArgumentNullException("source"); if (predicate == null) throw new ArgumentNullException("predicate"); return SkipFirstMatchingCore(source, predicate); } private static IEnumerable<T> SkipFirstMatchingCore<T> (IEnumerable<T> source, Func<T, bool> predicate) { bool itemToSkipSeen = false; foreach (T item in source) { if (!itemToSkipSeen && predicate(item)) itemToSkipSeen = true; else yield return item; } }
And use it like:
var list = new [] { 1,2,3,4,5,6,7,8,9 }; var skipFirstEvenNumber = list.SkipFirstMatching(i => i % 2 == 0);
By the way, your current code doesn't seem right at all. The variable is called skipFirstEvenNumber , but the request skips odd numbers. Secondly, you are trying to use a side effect to make the request work, but you only set the flag variable, not read it. Therefore, your current code should work like normal SkipWhile .
EDIT : make the right choice of arguments.
source share