C# TakeWhile Method

LINQ (language integrated query)

You want to use the TakeWhile method in the C# programming language. By passing a predicate function to TakeWhile, you can take elements until the condition no longer matches.

This C# article looks at the TakeWhile extension method from the System.Linq namespace.

Example

In this example program, an integer array of five elements is declared; the first three numbers in it are odd, while the last two are even. Next, the TakeWhile extension method is invoked: it is passed a predicate function in the form of a lambda expression. TakeWhile returns the first three odd numbers, but not the even numbers at the end.

Program that uses TakeWhile method [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Contains five numbers.
	int[] values = { 1, 3, 5, 8, 10 };

	// Take all non-even (odd) numbers.
	var result = values.TakeWhile(item => item % 2 != 0);

	// Display result.
	foreach (int value in result)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

1
3
5
Question and answer

Reading the lambda expression. How can you read the lambda expression? The name 'item' is just a temporary variable name. Each element becomes an item, and then the function returns true only if the value is not evenly divisible by two.

Lambda Expression Modulo Operator

Summary

The TakeWhile method is similar to the Take method, but uses a terminating predicate condition rather than an element count as a parameter. As long as that predicate returns true, the Take method proceeds. Instead of combining filtering extension methods and then using Take, you can use TakeWhile for improved simplicity.

Take LINQ Examples
.NET