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

適用対象

こちらもご覧ください