Performs the specified action on each element of the
List.
Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)

Syntax
Visual Basic (Declaration)
Public Sub ForEach ( _
action As Action(Of T) _
)
Dim instance As List(Of T)
Dim action As Action(Of T)
instance.ForEach(action)
public void ForEach (
Action<T> action
)
public:
void ForEach (
Action<T>^ action
)
public void ForEach (
Action<T> action
)
public function ForEach (
action : Action<T>
)
Parameters
- action
The Action delegate to perform on each element of the List.

Exceptions

Remarks
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.

Example
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.
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. |
Imports System
Imports System.Collections.Generic
Class Program
Shared Sub Main()
Dim names As New List(Of String)
names.Add("Bruce")
names.Add("Alfred")
names.Add("Tim")
names.Add("Richard")
' Display the contents of the List out imports the "Print" delegate.
names.ForEach(AddressOf Print)
End Sub
Shared Sub Print(ByVal s As String)
Console.WriteLine(s)
End Sub
End Class
' This code will produce output similar to the following:
' Bruce
' Alfred
' Tim
' Richard
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
*/

Platforms
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.

Version Information
.NET Framework
Supported in: 3.0, 2.0
.NET Compact Framework
Supported in: 2.0
XNA Framework
Supported in: 1.0

See Also