[LINQ Operators] TakeWhile

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

 

1. Sample Data Object

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

 

2. “TakeWhile” operator

  • Deferred operator
  • Purpose: Partitioning / Making a subset

 

3. Prototypes

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

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

The “TakeWhile()” operator returns a elements from an input sequence as long as a specified condition is true.

You need a predicate delegate 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.TakeWhile(e => e.Id < 3); // takes 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 “TakeWhile()” operator upon the whole query expression.

var emps = Employee.GetEmployees();

var newEmps
   = (from e in emps
      select e).TakeWhile(e => e.Id < 3); // takes 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.TakeWhile((e, i) => i < 3); // takes 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