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

定義

List<T> 的每一個項目上執行指定之動作。Performs the specified action on each element of the List<T>.

public:
 void ForEach(Action<T> ^ action);
public void ForEach (Action<T> action);
member this.ForEach : Action<'T> -> unit
Public Sub ForEach (action As Action(Of T))

參數

action
Action<T> Action<T> Action<T> Action<T>

要在 Action<T> 的每一個項目上執行的 List<T> 委派。The Action<T> delegate to perform on each element of the List<T>.

例外狀況

集合中的項目已經過修改。An element in the collection has been modified.

範例

下列範例示範如何使用Action<T>委派來列印List<T>物件的內容。The following example demonstrates the use of the Action<T> delegate to print the contents of a List<T> object. 在此範例中Print , 會使用方法, 將清單的內容顯示到主控台。In this example the Print method is used to display the contents of the list to the console.

注意

除了使用Print方法來顯示內容之外, 此C#範例還示範了匿名方法的使用方式, 以將結果顯示在主控台中。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 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
 */
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 using the Print method.
        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

備註

Action<T>是方法的委派, 可對傳遞給它的物件執行動作。The Action<T> is a delegate to a method that performs an action on the object passed to it. 目前List<T>的元素會個別傳遞Action<T>給委派。The elements of the current List<T> are individually passed to the Action<T> delegate.

這個方法是 O (n) 運算, 其中nCountThis method is an O(n) operation, where n is Count.

不支援修改委派主體中的基礎集合Action<T> , 而且會導致未定義的行為。Modifying the underlying collection in the body of the Action<T> delegate is not supported and causes undefined behavior.

適用於

另請參閱