# ASP.NET Razor C# Loops and Arrays
In ASP.NET Razor, loops are used to iterate through collections or perform repetitive tasks. The most commonly used loop constructs are `for`, `foreach`, and `while`.
## for Loop
The `for` loop is used when you know how many times you want to repeat an operation:
```csharp
@{
var numbers = new int[] { 1, 2, 3, 4, 5 };
}
@foreach (var number in numbers)
{
- @number
}
```
## foreach Loop
The `foreach` loop is ideal for iterating over arrays or collections:
```csharp
@{
var fruits = new string[] { "Apple", "Banana", "Orange" };
}
@foreach (var fruit in fruits)
{
- @fruit
}
```
## while Loop
The `while` loop continues to execute as long as a specified condition is true:
```csharp
@{
int i = 0;
var names = new string[] { "Alice", "Bob", "Charlie" };
}
@while (i < names.Length)
{
- @names
i++;
}
```
## Array Operations
Arrays in Razor can be manipulated using standard C# syntax:
```csharp
@{
var colors = new string[] { "Red", "Green", "Blue" };
var count = colors.Length;
}
There are @count colors.
```
You can also modify array elements directly:
```csharp
@{
var items = new int[] { 1, 2, 3, 4, 5 };
items = 10; // Change first element to 10
}
@foreach (var item in items)
{
- @item
}
```
These examples demonstrate basic usage of loops and arrays in ASP.NET Razor pages with C#. They provide a foundation for handling dynamic content and data manipulation in your web applications.