Visual C# 2005 Guide
For Each Loops

For each loops are used when you want to execute some code for every element in an array or arraylist. Arrays are ordered, arraylists are not. The for each loop is the most common way of iterating through each element in an arraylist.

ArrayList myList = new ArrayList();
int[] rangeToAdd = { 43, 27, 71, 19, 1, 38, 92, 53, 64 };
myList.AddRange(rangeToAdd);
int total = 0;
int numItems = myList.Count;
foreach (int myListItem in myList)
{
   total += myListItem;
}

Console.WriteLine("The total is {0}", total);
double meanOfItems = (double)total / numItems;
Console.WriteLine("The mean is {0}", meanOfItems);
Console.ReadLine();

Having A Go

  1. Use the arraylist data structure to store numbers entered at the keyboard by the user. When they enter 999, stop accepting numbers and report the largest, smallest, mean and total of the numbers entered.