0
0
CsharpHow-ToBeginner · 3 min read

How to Use List.ForEach in C# for Easy Item Processing

In C#, List.ForEach lets you run a specific action on every item in a list easily by passing a lambda expression or method. It simplifies looping through all elements without writing a traditional foreach loop.
📐

Syntax

The List.ForEach method takes one parameter: an Action<T> delegate that defines what to do with each item in the list.

Here is the syntax:

list.ForEach(item => { /* action using item */ });

- list: your List<T> object.
- item => { }: a lambda expression representing the action to perform on each element.

csharp
list.ForEach(item => { /* action on item */ });
💻

Example

This example shows how to use List.ForEach to print each number in a list to the console.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        numbers.ForEach(number => Console.WriteLine(number));
    }
}
Output
1 2 3 4 5
⚠️

Common Pitfalls

One common mistake is trying to use List.ForEach to modify the list items directly when they are value types like integers or structs. Since the lambda gets a copy of the item, changes inside the action do not affect the original list.

Also, List.ForEach cannot be used with IEnumerable<T> or arrays; it only works on List<T> objects.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3 };

        // Wrong: trying to modify items directly
        numbers.ForEach(n => n = n * 2);
        numbers.ForEach(n => Console.WriteLine(n)); // Prints original numbers

        // Right: modify list by index
        for (int i = 0; i < numbers.Count; i++)
        {
            numbers[i] = numbers[i] * 2;
        }
        numbers.ForEach(n => Console.WriteLine(n)); // Prints doubled numbers
    }
}
Output
1 2 3 2 4 6
📊

Quick Reference

  • Purpose: Run an action on each item in a List<T>.
  • Parameter: An Action<T> delegate (usually a lambda).
  • Does not modify list items if they are value types inside the lambda.
  • Only works on List<T>, not arrays or other collections.

Key Takeaways

Use List.ForEach to run simple actions on each list item with a lambda expression.
List.ForEach works only on List, not on arrays or other collections.
Modifying value type items inside ForEach does not change the original list elements.
For complex modifications, use a for loop with index access instead.
List.ForEach improves code readability by replacing explicit loops for simple actions.