Loops

If you want to run the same statement repeatedly you can use a loop:

  • A for-loop is used when you know how many times you want to loop, e.g. if you’re counting up or down
  • A foreach-loop is used to go through each member of a collection/array and do stuff until the end of the collection/array
  • A while-loop is used run a statement while some condition is true. It typically adds to or subtracts from a variable used for counting, making the loop end at some point

Here are a couple of examples:

RAZOR
<!--For loop--> @for (var i = 10; i < 21; i++) { <div>Line @i</div> } <!-- Foreach loop--> @foreach (var field in Model.Item.Fields) { <div>@field.Name</div> } <!--While loop--> @{ int z = 0; } @while (z < 5) { z += 1; <div>Line @z</div> }