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

Definicja

Wykonuje określoną akcję dla każdego elementu elementu 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))

Parametry

action
Action<T>

Delegat Action<T> do wykonania dla każdego elementu elementu List<T>.

Wyjątki

action to null.

Element w kolekcji został zmodyfikowany.

Przykłady

W poniższym przykładzie pokazano użycie delegata Action<T> do drukowania zawartości List<T> obiektu. W tym przykładzie Print metoda służy do wyświetlania zawartości listy w konsoli.

Uwaga

Oprócz wyświetlania zawartości przy użyciu metody w przykładzie Print języka C# pokazano użycie metod anonimowych do wyświetlania wyników w konsoli.

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

Uwagi

Element Action<T> jest delegatem do metody, która wykonuje akcję na przekazanym do niego obiekcie. Elementy bieżące List<T> są indywidualnie przekazywane do delegata Action<T> .

Ta metoda jest operacją O(n), gdzie n to Count.

Modyfikowanie podstawowej kolekcji w treści delegata Action<T> nie jest obsługiwane i powoduje niezdefiniowane zachowanie.

Dotyczy

Zobacz też