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"};
}
<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 (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>
@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 })