Summary: in this tutorial, you’ll learn how to use the LINQ ForEach()
method to execute an operation on each element of a sequence.
Introduction to the LINQ ForEach() method
The ForEach()
method allows you to execute an action on each element of a sequence.
Here’s the syntax of the ForEach()
method:
public static void ForEach<T>(
this IEnumerable<T> source,
Action<T> action
);
Code language: C# (cs)
In this syntax:
T
is the type of elements in thesource
sequence.source
is the input sequence that has theIEnumerable<T>
.action
is the operation that applies to each element of thesource
sequence.
LINQ ForEach examples
Let’s take some examples of using the LINQ ForEach()
method.
1) The basic LINQ ForEach() usage
The following example demonstrates how to use the ForEach()
method to write integers of a list to the console:
using static System.Console;
var numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.ForEach(WriteLine);
Code language: C# (cs)
Output:
1
2
3
4
5
Code language: C# (cs)
In this example, we pass the
method to the WriteLine
method. The ForEach()
method executes the ForEach()
method on each integer of the numbers list that writes each number to the console.WriteLine
2) Using LINQ ForEach() to calculate line total of products
The following example demonstrates how to use the ForEach()
method to calculate the line total of products:
class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public Product(string name, decimal price, int quantity)
{
Name = name;
Price = price;
Quantity = quantity;
}
}
class Program
{
static void Main(string[] args)
{
var products = new List<Product>()
{
new Product("Apple", 0.99m, 2),
new Product("Banana", 1.29m, 3),
new Product("Orange", 0.89m, 4),
new Product("Grapes", 2.49m, 1)
};
decimal total = 0m;
products.ForEach(product =>
{
decimal lineTotal = product.Price * product.Quantity;
Console.WriteLine($"{product.Name} x {product.Quantity}: {lineTotal:C}");
total += lineTotal;
});
Console.WriteLine($"Total: {total:C}");
}
}
Code language: C# (cs)
Output:
Apple x 2: $1.98
Banana x 3: $3.87
Orange x 4: $3.56
Grapes x 1: $2.49
Total: $11.90
Code language: C# (cs)
Summary
- Use the LINQ
ForEach()
method to apply an action on each element of a sequence.