Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

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

 

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

Namespace:   System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

public void ForEach(
	Action<T> action
)

Parameters

action
Type: System.Action<T>

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

Exception Condition
ArgumentNullException

action is null.

InvalidOperationException

An element in the collection has been modified.

System_CAPS_warningWarning

This exception is thrown starting with the .NET Framework 4.5.

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.

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.

System_CAPS_noteNote

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

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        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);
        });
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}
/* This code will produce output similar to the following:
 * Bruce
 * Alfred
 * Tim
 * Richard
 * Bruce
 * Alfred
 * Tim
 * Richard
 */

Universal Windows Platform
Available since 10
.NET Framework
Available since 2.0
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top
Show:
© 2017 Microsoft