#155 – Iterating Through an Array Using the foreach Statement
November 19, 2010 1 Comment
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.
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;
}
Pingback: #583 – You Can’t Modify the Iterator Variable Within a foreach Loop « 2,000 Things You Should Know About C#