C# Enumerable TakeWhile(IEnumerable, Func)
Description
Returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.
Syntax
public static IEnumerable<TSource> TakeWhile<TSource>(
this IEnumerable<TSource> source,
Func<TSource, int, bool> predicate
)
Parameters
TSource
- The type of the elements of source.source
- The sequence to return elements from.predicate
- A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
Example
The following code example demonstrates how to use TakeWhile to return elements from the start of a sequence as long as a condition that uses the element's index is true.
/*from www . ja va 2 s . c om*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
string[] fruits = { "apple", "orange", "blueberry", "grape", "strawberry" };
IEnumerable<string> query =
fruits.TakeWhile((fruit, index) => fruit.Length >= index);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
}
}
The code above generates the following result.