SuperLinq SuperLinq
SuperLinq SuperLinq
DocFX + Singulink = ♥

Search Results for

    Method While

    | Edit this page

    While<TSource>(Func<bool>, IEnumerable<TSource>)

    Generates an enumerable sequence by repeating a source sequence as long as the given loop condition holds.

    Declaration
    public static IEnumerable<TSource> While<TSource>(Func<bool> condition, IEnumerable<TSource> source)
    Parameters
    Type Name Description
    Func<bool> condition

    Loop condition.

    IEnumerable<TSource> source

    Sequence to repeat while the condition evaluates true.

    Returns
    Type Description
    IEnumerable<TSource>

    Sequence generated by repeating the given sequence while the condition evaluates to true.

    Type Parameters
    Name Description
    TSource

    Source sequence element type.

    Remarks

    condition is evaluated lazily, once at the start 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 while a condition is true using While.

    var sequence = Enumerable.Range(1, 2);
    
    // Repeat a sequence while a condition is true
    var count = 0;
    var result = SuperEnumerable
        .While(
            () => count++ < 3,
            sequence);
    
    Console.WriteLine(
        "[" +
        string.Join(", ", result) +
        "]");
    
    // This code produces the following output:
    // [1, 2, 1, 2, 1, 2]
    
    Exceptions
    Type Condition
    ArgumentNullException

    condition or source is null.

    © SuperLinq Authors. All rights reserved.