Skip and Take Examples (SkipWhile, TakeWhile)
This page was last reviewed on May 16, 2024.
Dot Net Perls
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.
Example. 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).
Part 1 We call Skip with an argument of 2. When we loop over the result, we print just the last 4 elements of the 6-element array.
Part 2 We use 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.
Part 3 For Take, we get a result that contains only the first elements. With an argument of 2, we get the first 2 elements.
Part 4 We use 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 Module
SKIP 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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 16, 2024 (new).
© 2007-2024 Sam Allen.