[LINQ Operators] SkipWhile

The “SkipWhile” operator skips elements from a sequence while a test is true and then returns the remainder of the sequence.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “SkipWhile” operator

  • Deferred operator
  • Purpose: Partitioning / Making a subset

 

3. Prototypes

public static IEnumerable<T> SkipWhile<T>(
  this IEnumerable<T> source,
  Func<T, bool> predicate)

public static IEnumerable<T> SkipWhile<T>(
  this IEnumerable<T> source,
  Func<T, int, bool> predicate)

The “SkipWhile()” operator bypasses elements from an input sequence as long as a specified condition is true and then returns the remaining elements.

You need a predicate delete which gets each element and returns “true” or “false”. The second prototype has another integer input argument; which is an index number (zero-based) for the element from the input sequence.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var newEmps
  = emps.SkipWhile(e => e.Id < 3);  // skips 1, 2

foreach (Employee e in newEmps)
{
  Console.WriteLine($"{e.Id}: {e.Name}";
}

 

5. Example 2 (Query Expression)

There’s no direct  translation to a query expression. But you can use the “SkipWhile()” operator upon the whole query expression.

var emps = Employee.GetEmployees();

var newEmps
  = (from e in emps
     select e)
     .SkipWhile(e => e.Id < 3); // skips 1, 2

foreach (Employee e in newEmps)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

 

6. Example 3 (Standard Operator): with an index number

var emps = Employee.GetEmployees();

var newEmps
  = emps.SkipWhile((e, i) => i < 3);  // skips 3 items (index 0, 1, 2)

foreach (Employee e in newEmps)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s