ASP.NET Razor - C# Loops and Arrays
Statements in a loop will be executed repeatedly.
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 usea for loop. This type of loop is especially useful when counting up or counting down:
Example
<body>
@for(var i = 10; i < 21; i++)
{<p>Line @i</p>}
</body>
</html>
Run example »
For Each Loop
If you are working with collections or arrays, you will often usea for each loop。
A collection is a group of similar objects. The for each loop can iterate through the collection until it is finished.
In the example below, the ASP.NET Request.ServerVariables collection is iterated through.
Example
<body>
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
</body>
</html>
Run example »
While Loop
The while loopis a general-purpose loop.
The while loop starts with the while keyword, followed by parentheses, inside which you can specify how long the loop will continue, and then the code block that is repeatedly executed.
A while loop usually sets an incrementing or decrementing variable for counting.
In the example below, the += operator adds 1 to the value of variable i each time the loop is executed.
Example
<body>
@{
var i = 0;
while (i < 5)
{
i += 1;
<p>Line @i</p>
}
}
</body>
</html>
Run example »
Arrays
When you need to store multiple similar variables but do not want to create a separate variable for each one, 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>
<body>
<h3>Members</h3>
@foreach (var person in members)
{
<p>@person</p>
}
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>
Run example »
Other Extensions