ASP.NET Razor - C# Loops and Arrays
Statements are repeated in a loop.
For Loop
If you need to repeat the same statement, you can set up a loop.
If you know the number of times to loop, you can use for loop. This type of loop is especially useful when counting up or down:
Example
@for(var i = 10; i < 21; i++)
{
Line @i
}Run Example »
For Each Loop
If you are using a collection or an array, you will often use a for each loop。
A collection is a group of similar objects, and a for each loop can iterate through the collection until completion.
In the example below, it iterates through the ASP.NET Request.ServerVariables collection.
Example
- @x }
@foreach (var x in Request.ServerVariables)
{
Run Example »
While Loop
while loopis a general-purpose loop.
A while loop starts with the while keyword, followed by parentheses in which you specify how long the loop will continue, then the code block to be repeated.
A while loop usually sets an incrementing or decrementing variable to count.
In the example below, the += operator adds 1 to the value of variable i each time the loop runs.
Example
@{
var i = 0;
while (i < 5)
{
i += 1;
Line @i
} }Run Example »
arrays
When you want 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];
}
Members
@foreach (var person in members)
{
@person
}The number of names in Members are
@len
The person at position 2 is
@x
Kai is now in position
@i
Run Example »