Skip
, Take
Suppose we want to loop over all the elements in an array except the first (or last) several elements. With Skip
and Take
, part of System.Linq
, we can do this in an elegant way.
With SkipWhile
and TakeWhile
, meanwhile, we can loop over elements only while a condition is true. So we can test the first elements for a condition with a Predicate
.
This VB.NET program uses Skip
and SkipWhile
, and then uses Take
and TakeWhile
. It calls all these methods on an array of 6 Integers (all odd numbers).
Skip
with an argument of 2. When we loop over the result, we print just the last 4 elements of the 6-element array.SkipWhile
to skip elements at the start of the collection that are less than or equal to 5. The first element we print is 7.Take
, we get a result that contains only the first elements. With an argument of 2, we get the first 2 elements.TakeWhile
with a lambda expression (similar to SkipWhile
) and it returns only the first elements that match the condition.Module Module1 Sub Main() Dim array() = { 1, 3, 5, 7, 9, 11 } ' Part 1: use Skip. Dim items1 = array.Skip(2) For Each value in items1 Console.WriteLine($"SKIP 2: {value}") Next ' Part 2: use SkipWhile. Dim items2 = array.SkipWhile(Function(x) Return x <= 5 End Function) For Each value in items2 Console.WriteLine($"SKIP WHILE <= 5: {value}") Next ' Part 3: use Take. Dim items3 = array.Take(2) For Each value in items3 Console.WriteLine($"TAKE 2: {value}") Next ' Part 4: use TakeWhile. Dim items4 = array.TakeWhile(Function(x) Return x <= 5 End Function) For Each value in items4 Console.WriteLine($"TAKEWHILE <= 5: {value}") Next End Sub End ModuleSKIP 2: 5 SKIP 2: 7 SKIP 2: 9 SKIP 2: 11 SKIP WHILE <= 5: 7 SKIP WHILE <= 5: 9 SKIP WHILE <= 5: 11 TAKE 2: 1 TAKE 2: 3 TAKEWHILE <= 5: 1 TAKEWHILE <= 5: 3 TAKEWHILE <= 5: 5
Skip
and Take
(along with SkipWhile
and TakeWhile
) are useful for enumerating only parts of a collection (like an array). We can avoid dealing with indexes in a For
-loop this way.