List<T>.ForEach(Action<T>) Method

Definition

Performs the specified action on each element of the List<T>.

C#
public void ForEach(Action<T> action);

Parameters

action
Action<T>

The Action<T> delegate to perform on each element of the List<T>.

Exceptions

action is null.

An element in the collection has been modified.

Examples

The following example demonstrates the use of the Action<T> delegate to print the contents of a List<T> object. In this example the Print method is used to display the contents of the list to the console.

Note

In addition to displaying the contents using the Print method, the C# example demonstrates the use of anonymous methods to display the results to the console.

C#
List<string> names = new List<string>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");

// Display the contents of the list using the Print method.
names.ForEach(Print);

// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(string name)
{
    Console.WriteLine(name);
});

void Print(string s)
{
    Console.WriteLine(s);
}

/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/

Remarks

The Action<T> is a delegate to a method that performs an action on the object passed to it. The elements of the current List<T> are individually passed to the Action<T> delegate.

This method is an O(n) operation, where n is Count.

Modifying the underlying collection in the body of the Action<T> delegate is not supported and causes undefined behavior.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

See also