List<T>.ForEach(Action<T>) メソッド

定義

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>

List<T> の各要素に対して実行する Action<T> デリゲート。

例外

actionnullです。

コレクションの要素が変更されています。

次の例では、 デリゲートを使用して Action<T> オブジェクトの内容を印刷する方法を List<T> 示します。 この例では、 メソッドを Print 使用して、リストの内容をコンソールに表示します。

注意

C# の例では、 メソッドを使用して Print コンテンツを表示するだけでなく、 匿名メソッド を使用して結果をコンソールに表示する方法も示しています。

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
*/
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>は、渡されたオブジェクトに対してアクションを実行するメソッドへのデリゲートです。 現在 List<T> の の要素は、デリゲートに個別に Action<T> 渡されます。

このメソッドは O(n) 操作です。 ここで、nCountです。

デリゲートの本体で基になるコレクションを Action<T> 変更することはサポートされておらず、未定義の動作が発生します。

適用対象

こちらもご覧ください