Friday, November 03, 2006

List.ForEach

The generic List class, introduced in .NET 2.0, has a ForEach method that lets you perform a specified action on each element of a list. The action can be declared using a delegate as either a named or anonymous method. Here's an example that prints the squares of numbers between 1 and 100 using an anonymous method:

// create a list of numbers, 1 to 100
List<int> nums = new List<int>();
for (int i = 1; i <= 100; i++) nums.Add(i);
 
// display the square of each number
nums.ForEach(
    delegate(int n) { Console.WriteLine(Math.Pow(n,2)); }
);

This excellent article, Performance of foreach vs. List.ForEach from Did it with .NET, compares List.ForEach with foreach and for loops and discusses the performance implications.

0 comments: