ASP.NET Razor - C# Loops and Arrays
Statements are executed repeatedly within a loop.
For Loop
If you need to execute the same statements repeatedly, you can set up a loop.
If you know the number of times you want to loop, you can use a for loop. This type of loop is particularly useful when counting up or down:
Example
@for(var i = 10; i < 21; i++)
{
<p>Line @i</p>
}
For Each Loop
If you are working with a collection or an array, you will frequently use a for each loop.
A collection is a group of similar objects, and a for each loop iterates through the collection until it is completed.
In the following example, the ASP.NET Request.ServerVariables collection is iterated through.
Example
@foreach (var x in Request.ServerVariables)
{
<li>@x</li>
}
While Loop
A while loop is a general-purpose loop.
A while loop begins with the while keyword, followed by parentheses where you specify how long the loop will continue, and then the block of code to be repeated.
A while loop typically sets an incrementing or decrementing variable for counting.
In the following example, the += operator increments the value of variable i by 1 each time the loop executes.
Example
@{
var i = 0;
while (i < 5)
{
i += 1;
<p>Line @i</p>
}
}
Arrays
When you need to store multiple similar variables but do not want to create a separate variable for each, you can use an array to store them:
Example
@{
string[] members = {"Jani", "Hege", "Kai", "Jim"};
int i = Array.IndexOf(members, "Kai") + 1;
int len = members.Length;
string x = members[2 - 1];
}
<html>
@foreach (var person in members)
{
<p>@person</p>
}
<p>@len</p>
<p>@x</p>
<p>@i</p>