Method DoWhile
| Edit this pageDoWhile<TSource>(IEnumerable<TSource>, Func<bool>)
Generates an enumerable sequence by repeating a source sequence as long as the given loop postcondition holds.
Declaration
public static IEnumerable<TSource> DoWhile<TSource>(this IEnumerable<TSource> source, Func<bool> condition)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<TSource> | source | Source sequence to repeat while the condition evaluates true. |
| Func<bool> | condition | Loop condition. |
Returns
| Type | Description |
|---|---|
| IEnumerable<TSource> | Sequence generated by repeating the given sequence until the condition evaluates to false. |
Type Parameters
| Name | Description |
|---|---|
| TSource | Source sequence element type. |
Remarks
condition is evaluated lazily, once at the end of each loop of source.
source is cached via Memoize<TSource>(IEnumerable<TSource>, bool), so that
it is only iterated once during the first loop. Successive loops will enumerate the cache instead of
source.
Examples
The following code example demonstrates how to repeat a sequence as long as a condition is true, using DoWhile.
var executionCount = 0;
var sequence = Enumerable.Range(1, 5)
.Do(_ => executionCount++);
// Execute an action for each element
var loopCount = 0;
var result = sequence
.DoWhile(() => loopCount++ < 2);
Console.WriteLine($"Before (execCount: {executionCount})");
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
Console.WriteLine($"After (execCount: {executionCount})");
// This code produces the following output:
// Before (execCount: 0)
// [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
// After (execCount: 5)
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException |
|