CSharp - TakeWhile operator with element index

Introduction

The following code will stop when an input element exceeds nine characters in length or when the sixth element is reached, whichever comes first.

Demo

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

Result

Related Topic