Latest web development tutorials

ASP.NET Razor C # loops, and arrays

Statements in the cycle will be repeated.


For loop

If you need to repeat the same statement, you can set up a cycle.

If you want to know the number of cycles, you can use the for loop. This type of loop is especially useful when counting up or counting down:

Examples

<html>
<body>
@for(var i = 10; i < 21; i++)
{<p>Line @i</p>}
</body>
</html>

Running instance »


For Each loop

If you are using a collection or array, you will be frequently used for each cycle.

A collection is a group of similar objects, for each loop can walk through the collection until completion.

The following examples, traversing ASP.NET Request.ServerVariables collection.

Examples

<html>
<body>
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
</body>
</html>

Running instance »


While loop

while loop is a common cycle.

while loop begins with the keyword while, followed by a parenthesis, you can specify how long the cycle will then repeat the code block is executed in parentheses.

while loop is usually set a variable to increment or decrement the count.

The following example, the + = operator to perform a loop at each value of the variable i is incremented.

Examples

<html>
<body>
@{
var i = 0;
while (i < 5)
{
i += 1;
<p>Line #@i</p>
}
}

</body>
</html>

Running instance »


Array

When you want to store a plurality of similar variables you do not want to have to create a separate variable for each variable but you can use an array to store:

Examples

@{
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>

Running instance »