TakeWhile Method

Returns elements from a sequence as long as a condition is met.

Copied!
public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

Parameters

Name Type Description
source IEnumerable<TSource> An IEnumerable<TSource> whose elements to return.
predicate Func<TSource, bool> A function to test each element for a condition.

Overloads

There are multiple overloads for this method, including one that provides the element's index:

Copied!
public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
Name Type Description
source IEnumerable<TSource> An IEnumerable<TSource> whose elements to return.
predicate Func<TSource, int, bool> A function to test each element for a condition; the second parameter of the function is the index of the element.

Remarks

The TakeWhile extension method returns elements from a sequence as long as the specified predicate returns true. The enumeration stops as soon as the predicate returns false. If the predicate never returns false, all elements are returned.

This method has a deferred execution behavior.

Example

Copied!
// Sample data
var numbers = new[] { 5, 4, 2, 3, 10, 9, 7 };

// Get elements as long as they are less than 10
var subset = numbers.TakeWhile(n => n < 10);

// The subset will contain: 5, 4, 2, 3
// 10 is the first element that fails the condition, so it and subsequent elements are excluded.

// Outputting the result (for demonstration)
foreach (var num in subset)
{
    Console.Write(num + " ");
}
// Output: 5 4 2 3

See Also