Razor C# Loops
Loops in Razor allow you to perform repetitive tasks in your server-side logic. Razor supports all C# loop structures, including for
, foreach
, while
, and do-while
, enabling you to iterate through collections or execute code multiple times.
Key Topics
For Loop
Example
@{
for (int i = 1; i <= 5; i++)
{
<p>Iteration @i</p>
}
}
Explanation: This example demonstrates the use of a for
loop to iterate through numbers 1 to 5, dynamically generating a paragraph for each iteration.
Foreach Loop
Example
@{
var fruits = new[] { "Apple", "Banana", "Cherry" };
foreach (var fruit in fruits)
{
<li>@fruit</li>
}
}
Explanation: The foreach
loop iterates through a collection, such as an array, and dynamically renders a list item for each element.
While Loop
Example
@{
int count = 1;
while (count <= 3)
{
<p>Count: @count</p>
count++;
}
}
Explanation: The while
loop continues to execute as long as the condition is true. This example dynamically renders the count until it reaches 3.
Key Takeaways
- Loops in Razor follow standard C# syntax.
- Use
for
loops for indexed iterations andforeach
for collections. - The
while
loop executes as long as its condition remains true.