List<T>.ForEach(Action<T>) Método
Definición
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))
Parámetros
- action
- Action<T>
Delegado Action<T> para realizar la acción en cada elemento de List<T>.The Action<T> delegate to perform on each element of the List<T>.
Excepciones
action
es null
.action
is null
.
Un elemento de la colección se ha modificado.An element in the collection has been modified.
Ejemplos
En el siguiente ejemplo se muestra el uso del Action<T> delegado para imprimir el contenido de un List<T> objeto.The following example demonstrates the use of the Action<T> delegate to print the contents of a List<T> object. En este ejemplo, el Print
método se usa para mostrar el contenido de la lista en la consola.In this example the Print
method is used to display the contents of the list to the console.
Nota
Además de mostrar el contenido mediante el Print
método, en el ejemplo de C# se muestra el uso de métodos anónimos para mostrar los resultados en la consola.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.
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
Comentarios
Action<T>Es un delegado de un método que realiza una acción en el objeto que se le ha pasado.The Action<T> is a delegate to a method that performs an action on the object passed to it. Los elementos del actual List<T> se pasan individualmente al Action<T> delegado.The elements of the current List<T> are individually passed to the Action<T> delegate.
Este método es una operación O (n), donde n es Count .This method is an O(n) operation, where n is Count.
No se admite la modificación de la colección subyacente en el cuerpo del Action<T> delegado y se produce un comportamiento indefinido.Modifying the underlying collection in the body of the Action<T> delegate is not supported and causes undefined behavior.