C# Enumerable TakeWhile(IEnumerable, Func)
Description
Returns elements from a sequence as long as a specified condition is true.
Syntax
public static IEnumerable<TSource> TakeWhile<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
Parameters
TSource
- The type of the elements of source.source
- A sequence to return elements from.predicate
- A function to test each element for a condition.
Example
The following code example demonstrates how to use TakeWhile to return elements from the start of a sequence as long as a condition is true.
//from w ww. j a v a2 s .c om
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
string[] fruits = { "apple", "banana","grape" };
IEnumerable<string> query =
fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
}
}
The code above generates the following result.