Skip to main content
Home  › ... Razor

Basic Tutorials

Tutorial HomeBasics

Loops - for and foreach

Using a foreach - the most common way of looping

Initial Code

The following code runs at the beginning and creates some variables/services used in the following samples.

@{
  var pets = new string[] { "dog", "cat", "mouse"};
  var owners = new string[] { "Daniel", "John", "Markus"};
}

Output

  • dog
  • cat
  • mouse
<ul>
  @foreach (var pet in pets) {
    <li>@pet</li>
  }
</ul>

Basic for

Output

  • dog
  • cat
  • mouse
<ul>
   @for(var i = 0; i < pets.Length; i++) {
     <li>@pets[i]</li>
   }
 </ul>

Using a for index with two lists (arrays)

Output

  • dog - owned by Daniel
  • cat - owned by John
  • mouse - owned by Markus
<ul>
   @for(var i = 0; i < pets.Length; i++) {
     <li>@pets[i] - owned by @owners[i]</li>
   }
 </ul>

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor14
<!-- unimportant stuff, hidden -->


<div @Sys.PageParts.InfoWrapper()>
  @Html.Partial("../shared/DefaultInfoSection.cshtml")
  <div @Sys.PageParts.InfoIntro()>
    <h2>Loops - <code>for</code> and <code>foreach</code></h2>
  </div>
</div>
<h3>Using a <code>foreach</code> - the most common way of looping</h3>

  @{
    var pets = new string[] { "dog", "cat", "mouse"};
    var owners = new string[] { "Daniel", "John", "Markus"};
  }


  <ul>
    @foreach (var pet in pets) {
      <li>@pet</li>
    }
  </ul>



Basic for

 <ul>
    @for(var i = 0; i < pets.Length; i++) {
      <li>@pets[i]</li>
    }
  </ul>


Using a for index with two lists... <!-- unimportant stuff, hidden -->

 <ul>
    @for(var i = 0; i < pets.Length; i++) {
      <li>@pets[i] - owned by @owners[i]</li>
    }
  </ul>



@* Footer *@
@Html.Partial("../Shared/Layout/FooterWithSource.cshtml", new { Sys = Sys })