Blazor for loop

Loops are used to execute a block of code repeatedly. For example, instead of

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
</ul>

You can write the following:

<ul>
    @for (int x=1;x<6;x++)
    {
        <li>
            Item @x
        </li>
    }
</ul>

A for loop has the following syntax:

for (expression 1; expression 2; expression 3) {
    code block to be executed
}

expression 1 is used for initializing a value (var x = 1) to a variable before the loop starts; expression 2 defines the condition (x < 6) for the loop to continue running; expression 3 is used for updating the variable value (x++) before the next iteration.

Besides incrementing the variable values, you can choose to decrement it in the same manner:

<ul>
  @for (int x = 5; x > 0; x--)
  {
    <li>
      Item @x
    </li>
  }
</ul>

This will return the following:

<ul>
  <li>Item 5</li>
  <li>Item 4</li>
  <li>Item 3</li>
  <li>Item 2</li>
  <li>Item 1</li>
</ul>

Omission of expression in a for loop

It is possible to omit the expressions in the for loop, For example, the following gives you an infinite loop:

@for ( ; ; )
{
  Item            
}

The for loop is also commonly used to loop through items (though we typically recommend a foreach loopa> for such purpose) in an array as follows:

@page "/"    
<ul>
@for (int x = 0; x < @items.Length; x++)
{       
  <li>
    @items[@x]
  </li>
}
</ul>

@functions {
  string[] items = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
}

Break or Continue

Sometimes, you may need to skip an iteration of the loop or maybe stop the entire loop when some condition occurs. This is when the break and continue keyword comes in useful. The break will exit the loop completely, continue will just skip the current iteration.

In the following example, the else part will not be executed when x is 0. Thus the continue keyword helps skip the iteration when x is 0.

<ul>
  @for (int x = 0; x < 6; x++)
  {
      if (x == 0)
      {
          continue;
      }
      else
      {
          <li>
              Item @x
          </li>
      }
  }
</ul>

In the following, none of the items will be displayed. This is because when x is 0, the break portion will be executed and the for loop will be skipped entirely.

<ul>
  @for (int x = 0; x < 6; x++)
  {
      if (x == 0)
      {
        break;
      }
      else
      {
        <li>
          Item @x
        </li>
      }
  }
</ul>