
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Performing an Action on Each Element in an Array or List<T>
|
319
// Display them.
foreach (Data d in numbers)
Console.WriteLine(d.val);
// Total val integer values in all Data objects in the List.
int total = 0;
numbers.ForEach(delegate(Data obj)
{
total += obj.val;
});
// Display total.
Console.WriteLine("Total: " + total);
This code outputs the following:
1
2
3
4
3
4
5
6
Total: 18
The Data class is defined as follows:
public class Data
{
public Data(int v)
{
val = v;
}
public int val = 0;
}
Discussion
The ForEach method of the Array and List<T> collections allows you to easily per-
form an action on every element within these collections. This is accomplished
through the use of the
Action<T> delegate, which is passed in as a parameter to the
ForEach method:
public void ForEach (Action<T> action)
The action parameter is a delegate of type Action<T> that contains the code that will
be invoked for each element of the collection.
The
ForEach method basically consists of a loop that iterates over each element in the
collection. Within this loop, a call to the
action delegate is invoked. Processing con-
tinues on to each element in the collection until the last element is finished process-
ing. When this occurs, the
ForEach method is finished and returns to the calling
method.