CSharp - LINQ TakeWhile

Introduction

The TakeWhile operator yields elements from an input sequence while some condition is true.

It starts from the beginning of the sequence.

The remaining input elements will be skipped.

Prototypes

There are two prototypes for the TakeWhile operator we will cover.

The First TakeWhile Prototype

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

The TakeWhile operator above accepts an input source sequence and a predicate method delegate.

It returns an object that, when enumerated, yields elements until the predicate method returns false.

The predicate method receives one element at a time from the input sequence and returns whether the element should be included in the output sequence.

It continues processing input elements until the predicate method returns false, no further input elements will be processed.

The Second TakeWhile Prototype

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

This prototype's predicate method will be passed a zero-based index of the element in the input source sequence.

Exceptions

ArgumentNullException is thrown if any arguments are null.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from  w w w. j  a v a  2s. c  om
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        IEnumerable<string> items = codeNames.TakeWhile(s => s.Length < 10);
        
        foreach (string item in items)
          Console.WriteLine(item);

    }
}

Result

The code above retrieved input elements until we hit one ten or more characters long.

Related Topics