System.Linq.Enumerable.ForEach Method

Namespace: System.Linq

Executes a transformational function on each element of a sequence.

public static void ForEach<TSource>(
    this IEnumerable<TSource> source,
    Action<TSource> action
)

Parameters

Name Type Description
source IEnumerable<TSource> An IEnumerable<T> whose elements to process.
action Action<TSource> An Action<T> delegate to execute for each element in the sequence.

Type Parameters

TSource: The type of the elements of source.

Remarks

The ForEach method is a convenient extension method for executing an action on each element of an IEnumerable<T>. It's important to note that ForEach does not return a new sequence; it performs a side effect for each element.

This method is primarily useful for scenarios where you want to perform an operation on each item without necessarily transforming the collection into a new one, such as logging, printing, or updating state.

Exceptions

Examples

Printing each number in a list:

using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        numbers.ForEach(Console.WriteLine);
        // Output:
        // 1
        // 2
        // 3
        // 4
        // 5

        // Performing a side effect: incrementing each number
        numbers.ForEach(n =>
        {
            // In a real scenario, you might modify an object or update a database
            Console.WriteLine($"Processing {n}");
        });
    }
}