ASP.NET Razor - C# Loops and Arrays
- Previous Page Razor C# Variable
- Next Page Razor C# Logic
Statements can be executed repeatedly within the loop.
For Loop
If you need to repeatedly execute the same statement, you can write a loop.
If you can determine the number of times the loop runs, you can use for loop. This type of loop is designed specifically for counting or reverse counting:
Example
<html> <body> @for(var i = 10; i < 21; i++) {<p>Line @i</p>} </body> </html>
Run Example
For Each Loop
If you need to process a collection or an array, you usually need to use for each loop.
A collection is a set of similar objects, and the 'for each' loop allows you to perform a task on each item once. The 'for each' loop will iterate over the collection until it is completed.
The following example traverses the ASP.NET Request.ServerVariables collection.
Example
<html> <body> <ul> @foreach (var x in Request.ServerVariables) {<li>@x</li>} </ul> </body> </html>
Run Example
While Loop
While is a general-purpose loop.
While LoopThe while loop starts with the keyword while, followed by parentheses, which define the duration of the loop, and then the code block to be looped.
The while loop usually increments or decrements the counting variable.
In the following example, the += operator increases the variable i by 1 each time the loop runs.
Example
<html> <body> @{ var i = 0; while (i < 5) { i += 1; <p>Line #@i</p> } } </body> </html>
Run Example
Array
If you need to store similar variables but do not want to create a separate variable for each item, arrays come in handy:
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 members in Members is: @len</p> <p>Person at position 2: @x</p> <p>Kai is located at position: @i</p> </body> </html>
Run Example
- Previous Page Razor C# Variable
- Next Page Razor C# Logic