Iterating Through an Array Using the foreach Statement


You can write a loop–a block of code that is executed more than once–that executes once for each element in an array, using the C# foreach statement.
The foreach statement declares a variable local to the loop of the same type of the elements in the array.  This variable takes on the value of each element in the array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Person[] folks = new Person[4];
folks[0] = new Person("Bronte", "Emily");
folks[1] = new Person("Bronte", "Charlotte");
folks[2] = new Person("Tennyson", "Alfred");
folks[3] = new Person("Mailer", "Norman");
 
string sLastNameList = "";
 
// For each Person in array, dump out name and concatenate last name
foreach (Person p in folks)
{
    Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
    sLastNameList += p.LastName;
}