Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET razor C# loops and arrays


May 12, 2021 ASP.NET


Table of contents


ASP.NET Razor - C-loops and arrays


Statements are repeated in a loop.

Loop statements allow us to execute a statement or group of statements multiple times.


For loop

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

If you know how many times you want to loop, you can use for loops. This type of loop is especially useful when counting up or down:

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

Run an instance . . .


For Each loop

If you're using a collection or array, you'll often use the for each loop.

A collection is a similar set of objects, and the for each loop can traverse the collection until it is complete.

In the following example, traversing ASP.NET request.ServerVariables collection.

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

Run an instance . . .


While loop

The while loop is a generic loop.

The while loop starts with the while keyword, followed by parentheses, in which you can specify how long the loop will last, followed by a block of code that repeats.

While loops typically set an incremental or decreasing variable to count.

In the following example, the operator adds 1 to the value of variable i for each loop.

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

</body>
</html>

Run an instance . . .


Array

When you want to store multiple similar variables but don't want to create a separate variable for each variable, you can use arrays to store:

@{
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 an instance . . .

Related articles

The C-loop