public static void Each<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
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.
The enumerable collection of elements to process.
The delegate (or lambda expression) representing the action to perform on each element.
This method does not return a value. Its primary purpose is to execute the provided action.
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.
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}"));
}
}
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()}!"));
}
}