Method TakeUntil
| Edit this page View SourceTakeUntil<TSource>(IEnumerable<TSource>, Func<TSource, bool>)
Takes items from the input sequence until the given predicate returns true when applied to the current source item; that item will be the last taken.
Declaration
public static IEnumerable<TSource> TakeUntil<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
Parameters
Type | Name | Description |
---|---|---|
IEnumerable<TSource> | source | Source sequence |
Func<TSource, bool> | predicate | Predicate used to determine when to stop yielding results from the source. |
Returns
Type | Description |
---|---|
IEnumerable<TSource> | Items from the source sequence until the |
Type Parameters
Name | Description |
---|---|
TSource | Type of the source sequence |
Remarks
TakeUntil differs from TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource, bool>) in two respects.
Firstly, the sense of the predicate is reversed: it is expected that the predicate will return false to start with, and then return true - for example, when trying to find a matching item in a sequence.
Secondly, TakeUntil returns the element which causes the predicate to return true.
This operator uses deferred execution and streams its result.
Examples
The following code example demonstrates how to take elements in a sequence until a condition is true using TakeUntil
.
var sequence = Enumerable.Range(1, 10);
// Take elements until the condition is true
var result = sequence
.TakeUntil(x => x == 5);
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
// This code produces the following output:
// [1, 2, 3, 4, 5]
Exceptions
Type | Condition |
---|---|
ArgumentNullException |
|