typestar

TakeWhile & SkipWhile in C#

Cut a sequence at the first element that breaks the rule.

var readings = new[] { 1, 2, 4, 8, 3, 1, 9 };

// TakeWhile stops at the first failure; Where would keep going
Console.WriteLine(string.Join(",", readings.TakeWhile(r => r < 5)));
Console.WriteLine(string.Join(",", readings.Where(r => r < 5)));

// SkipWhile drops the prefix, then keeps everything after it
Console.WriteLine(string.Join(",", readings.SkipWhile(r => r < 5)));

// Take and Skip page through by count
Console.WriteLine(string.Join(",", readings.Skip(2).Take(3)));

How it works

  1. TakeWhile stops at the first failure; Where would keep filtering.
  2. SkipWhile drops the prefix and keeps everything after it.
  3. Skip(2).Take(3) pages by count instead of by condition.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
479
Tokens
118
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 1 of 3 in Slicing, step 4 of 17 in LINQ in depth.

← Previous Next →