CodeBlanks Logo Icon CodeBlanks

Take and Skip

C# course · Intermediate · Lesson 97/116

Learn slicing with Take, Skip, TakeWhile and SkipWhile.

Slicing with Take and Skip

Take(n) takes the first n elements of a collection. Skip(n) skips the first n and returns the rest. Both are deferred; the result is again an IEnumerable<T>.

For pagination you combine them: 5 items on page 2 is items.Skip(5).Take(5). This pattern also shows up in database queries. Taking more than available is safe; Take returns what it has.

TakeWhile and SkipWhile

TakeWhile(condition) takes elements from the start as long as the condition holds; it stops at the first mismatch. SkipWhile(condition) skips from the start as long as the condition holds; it returns everything from the first mismatch onward.

Example: new[] { 2, 4, 6, 7, 8 }.TakeWhile(n => n % 2 == 0) yields { 2, 4, 6 }; 7 is odd, so it stops. These methods are useful for finding patterns in ordered data.

Exercise Take the first three

Take the first three elements of numbers with Take(3) and print each in a foreach loop.

Show example solution
Take the first three with numbers.Take(3), loop with foreach, print with Console.WriteLine(n).
Example solution:
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 10, 20, 30, 40, 50 };
        foreach (var n in numbers.Take(3))
        {
            Console.WriteLine(n);
        }
    }
}

Test yourself

  1. How is pagination done?

    • Take(5).Skip(5)
    • Skip(5).Take(5)
    • Skip(5).Distinct()
    • Take(5).Where(...)
    Show answer

    Skip(5).Take(5) — Correct. First Skip past the earlier pages, then Take the items of the target page.

  2. Match each method to its result

    Take(3)
    First three
    Skip(3)
    Skip first three
    TakeWhile(...)
    Until break
    SkipWhile(...)
    After break
  3. Complete the Take call

    var first3 = numbers.____(3);
    Show answer
    var first3 = numbers.Take(3);

All lessons in Intermediate