Linq skips first where (linq to objects)

I need to skip the first element that matches the predicate as a linq query. As far as I can tell, I can do something like this:

var list = new [] {1,2,3,4,5,6,7,8,9}; var skippedFirstOdd = false; var skipFirstEvenNumber = list.SkipWhile(number => { if(number % 2 != 0) { skippedFirst = true; return true; } else { return false; } }); 

Which works (I think), but not very elegant. Is there a cleaner way to achieve this?

+4
source share
1 answer

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.

+7
source

Source: https://habr.com/ru/post/1343756/


All Articles