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.ForEach Method

Performs the specified action on each element of the List.

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

public void ForEach (
	Action<T> action
)
public void ForEach (
	Action<T> action
)
public function ForEach (
	action : Action<T>
)
Not applicable.

Parameters

action

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

Exception typeCondition

ArgumentNullException

action is a null reference (Nothing in Visual Basic).

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

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

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

NoteNote:

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.

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 out using the "Print" delegate.
        names.ForEach(Print);

        // The following demonstrates the Anonymous Delegate 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
 */

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

.NET Compact Framework

Supported in: 2.0

XNA Framework

Supported in: 1.0
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft