Enumerable.TakeWhile Method

Namespace: System.Linq

Assembly: System.Linq.dll

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

Returns elements from a sequence as long as a generated condition is true. To-translate-into-other-languages.

Parameters

source

An IEnumerable<TSource> to return elements from.

predicate

A function to test each element for a condition.

Generic Type Parameters

TSource

The type of the elements of source.

Returns:

An IEnumerable<TSource> that contains elements from the input sequence as long as the predicate is true.

Example

The following code example demonstrates how to use the TakeWhile method to return elements from a sequence until a condition is no longer met.


using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        // Take elements as long as they are less than 5
        IEnumerable<int> firstFew = numbers.TakeWhile(n => n < 5);

        Console.WriteLine("Elements taken while less than 5:");
        foreach (int number in firstFew)
        {
            Console.WriteLine(number);
        }
        // Output:
        // 1
        // 2
        // 3
        // 4
    }
}
                    

Remarks

The TakeWhile method returns elements from the beginning of the sequence as long as the specified predicate returns true. As soon as the predicate returns false for an element, the method stops processing and does not include that element or any subsequent elements.

If the input sequence is empty, TakeWhile returns an empty sequence.