List<T>.ForEach(Action<T>) メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
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 は nullです。
コレクション内の要素が変更されました。
例
次の例では、 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) 演算であり、 n は Count。
Action<T> デリゲートの本体で基になるコレクションを変更することはサポートされておらず、未定義の動作が発生します。