The statement is repeated in the loop.
For loop
If you need to execute the same statement repeatedly, you can set 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:
Examples <body>
@for (var i = ten; i <; i++)
{<p>line @i</p>}
</body>
Running Instances»
For Each loop
If you are using a collection or an array, you will often use the for each loop .
A collection is a set of similar objects that can be traversed by a for Each loop until it is complete.
In the following instance, traverse the ASP. NET Request.ServerVariables collection.
Examples <body>
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
</body>
Running Instances»
While loop
The while Loop is a common loop.
While loops start with the while keyword followed by parentheses, you can specify in parentheses how long the loop will last, followed by a code block that repeats.
The while loop usually sets an increment or decrement variable to count.
In the following instance, the + = operator adds 1 to the value of the variable i when each loop is executed.
Examples <body>
@{
var i = 0;
while (I < 5)
{
i + = 1;
<p>line #@i</p>
}
}
</body>
Running Instances»
Array
When you want to store multiple similar variables but do not want to create a separate variable for each variable, you can use an array to store:
Instance@{
String[] Members = {"Jani", "Hege", "Kai", "Jim"};
int i = Array.indexof (members, "Kai") +1;
int len = Members. Length;
string x = members[2-1];
}
<body>
@foreach (var person in members)
{
<p> @person </p>
}
<p>the number of names in members is @len </p>
<p>the person at position 2 is @x</p>
<p>kai is now in position @i</p>
</body>
Running Instances»
ASP. NET razor-c# Loop and array