SuperLinq SuperLinq
SuperLinq SuperLinq
DocFX + Singulink = ♥

Search Results for

    Method ForEach

    | Edit this page

    ForEach<TSource>(IEnumerable<TSource>, Action<TSource>)

    Immediately executes the given action on each element in the source sequence.

    Declaration
    public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
    Parameters
    Type Name Description
    IEnumerable<TSource> source

    The sequence of elements

    Action<TSource> action

    The action to execute on each element

    Type Parameters
    Name Description
    TSource

    The type of the elements in the sequence

    Remarks

    This operator executes immediately.

    Examples

    The following code example demonstrates how to immediately execute an action on every element of a sequence using ForEach.

    var sequence = Enumerable.Range(1, 5);
    
    // Fold a sequence into a single value.
    sequence
        .ForEach(x => Console.Write($"{x}, "));
    
    // This code produces the following output:
    // 1, 2, 3, 4, 5, 
    
    Exceptions
    Type Condition
    ArgumentNullException

    source or action is null.

    | Edit this page

    ForEach<TSource>(IEnumerable<TSource>, Action<TSource, int>)

    Immediately executes the given action on each element in the source sequence. Each element's index is used in the logic of the action.

    Declaration
    public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource, int> action)
    Parameters
    Type Name Description
    IEnumerable<TSource> source

    The sequence of elements

    Action<TSource, int> action

    The action to execute on each element; the second parameter of the action represents the index of the source element.

    Type Parameters
    Name Description
    TSource

    The type of the elements in the sequence

    Remarks

    This operator executes immediately.

    Examples

    The following code example demonstrates how to immediately execute an action on every element of a sequence using ForEach.

    var sequence = Enumerable.Range(1, 5);
    
    // Fold a sequence into a single value.
    sequence
        .ForEach((x, i) => Console.Write($"({x}, {i}), "));
    
    // This code produces the following output:
    // (1, 0), (2, 1), (3, 2), (4, 3), (5, 4), 
    
    Exceptions
    Type Condition
    ArgumentNullException

    source or action is null.

    © SuperLinq Authors. All rights reserved.