A while loop is used to execute a block of codes repeatedly. The loop begins with the while keyword, followed by a condition, if true, to continue executing the loop.
For example, you can write the following:
<ul>
@{
var i = 1;
while (i < 6)
{
<li>Item @i</li>
i++;
}
}
</ul>
to get
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
You can also use a while loop to loop through an array of objects as shown below:
<ul>
@{
string[] items = { "Item 1", "Item 2", "Item 3" };
var x = 0;
while (x < items.Length)
{
<li>@items[x]</li>
x++;
}
}
</ul>
A do loop is used to execute a blocks of code repeatedly. The loop begins with the do keyword, followed by the block of codes to execute repeatedly, and a while keyword with the condition to continue to execute the loop.
<ul>
@{
var i = 1;
do
{
<li>Item @i</li>
i++;
}
while (i < 6);
}
</ul>
The do loop above will give you the following:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
You can also use a do while loop to loop through an array of objects as shown below:
@page "/"
<ul>
@{
Item[] Items = {
new Item("Item 1","12345"),
new Item("Item 2","12346"),
new Item("Item 3","12347")
};
var i = 0;
do
{
<li>@Items[i].Name</li>
i++;
}
while (i < Items.Length);
}
</ul>
@functions {
public class Item
{
public Item(string name, string id)
{
Name = name;
Id = id;
}
public string Name { get; set; }
public string Id { get; set; }
}
}