Foreach loop
From Coderwiki
More actions
(Redirected from For each loop)
A foreach loop is an iteration structure in code which allows us to loop through a code block for each element in a collection.
It is a form of definite iteration, or count-controlled iteration.
Example
edit edit source
In the below C Sharp code, we loop through the values of the fruits array and print out each element:
string[] fruits = {"Banana", "Apple", "Peach", "Strawberry", "Raspberry"};
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
The code above will give the following output:
Banana Apple Peach Strawberry Raspberry
Iterating a range of values
edit edit sourceIf you instead want to loop over a range of integers or another type of range, you should instead use a regular for loop.
See: For loop