ASP.NET Razor - VB Loop and Array

The statement 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 i=10 To 21
    @<p>Line #@i</p>
Next i
</body>
</html>

Run Example

For Each Loop

If you need to process a collection or 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 traverse the collection until completion.

The following example traverses the ASP.NET Request.ServerVariables collection.

Example

<html>
<body>
<ul>
@For Each x In Request.ServerVariables
    @<li>@x</li>
Next x
</ul>
</body>
</html>

Run Example

While Loop

While is a general-purpose loop.

The while loop starts with the keyword while, followed by an expression that defines the length 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 is used to increment the variable i each time the loop runs.

Example

<html>
<body>
@Code
Dim i=0
Do While i<5
    i += 1
    @<p>Line #@i</p>
Loop
End Code
</body>
</html>

Run Example

Array

If you need to store similar variables but do not want to create a separate variable for each item, then an array comes in handy:

Example

@Code
Dim members As String()={"Jani","Hege","Kai","Jim"}
i=Array.IndexOf(members,"Kai")+1
len=members.Length
x=members(2-1)
end Code
<html>
<body>
<h3>Members</h3>
@For Each person In members
   @<p>@person</p>
Next Person
<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