December 2007
Intermediate to advanced
896 pages
19h 57m
English
You need an easy way to iterate over all the elements in an Array or List<T>, performing an operation on each element as you go.
Use the ForEach method of the Array or List<T> classes:
// Create and populate a List of Data objects.
List<Data> numbers = new List<Data>()
{new Data(1), new Data(2), new Data(3), new Data(4)};
// Display them.
foreach (Data d in numbers)
Console.WriteLine(d.val);
// Add 2 to all Data.val integer values.
numbers.ForEach(delegate(Data obj) { obj.val += 2; });
// 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;
}The ForEach method of the Array and List<T> collections allows you to easily perform 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 ...
Read now
Unlock full access