.NET API Documentation

Microsoft.NET.Sdk.Web

Enumerable.Each Method

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

Description

Executes a given action on each element of an enumerable collection. This is a convenient extension method for iterating through collections and performing an operation on each item.

This method is a helper for common LINQ scenarios where you need to perform a side effect for each element, such as logging, printing to the console, or updating a UI element.

Parameters

Returns

This method does not return a value. Its primary purpose is to execute the provided action.

Remarks

The Each method is part of the System.Linq.Enumerable class, providing functional programming capabilities to C# collections.

It is important to note that the action delegate is executed sequentially for each element. If the collection is extremely large, consider the performance implications.

The generic type parameter TSource represents the type of the elements in the source collection.

Examples

Example 1: Printing numbers to the console


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

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

        numbers.Each(num => Console.WriteLine($"Processing: {num}"));
    }
}
            

Example 2: Modifying a list of strings


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

public class Example
{
    public static void Main(string[] args)
    {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

        names.Each(name => Console.WriteLine($"Hello, {name.ToUpper()}!"));
    }
}