ASP.NET Razor – C# Loops and Arrays

Welcome to The Coding College, your one-stop destination for learning web development. In this tutorial, we’ll explore how to use C# loops and arrays in ASP.NET Razor. Loops and arrays are powerful tools that allow you to dynamically handle repetitive tasks and collections of data in your web pages.

What Are Loops and Arrays in Razor?

Loops

Loops in Razor allow you to execute a block of code multiple times based on a condition or the size of a collection.

Arrays

Arrays are a collection of items stored under a single variable name, enabling you to manage related data efficiently.

Using Arrays in Razor

1. Declaring and Initializing Arrays

You can declare arrays using the new keyword or initialize them directly.

Example: Declaring an Array

@{
    string[] fruits = new string[3];
    fruits[0] = "Apple";
    fruits[1] = "Banana";
    fruits[2] = "Cherry";
}

Example: Initializing an Array

@{
    string[] fruits = { "Apple", "Banana", "Cherry" };
}

Using Loops with Razor

1. The for Loop

The for loop executes a block of code a specific number of times.

Example: Iterating Through an Array

@{
    string[] fruits = { "Apple", "Banana", "Cherry" };
}
<ul>
    @for (int i = 0; i < fruits.Length; i++)
    {
        <li>@fruits[i]</li>
    }
</ul>

2. The foreach Loop

The foreach loop iterates over each item in a collection or array.

Example: Rendering a List

@{
    string[] fruits = { "Apple", "Banana", "Cherry" };
}
<ul>
    @foreach (var fruit in fruits)
    {
        <li>@fruit</li>
    }
</ul>

3. The while Loop

The while loop continues to execute as long as its condition is true.

Example: Loop with a Counter

@{
    int counter = 0;
}
<ul>
    @while (counter < 3)
    {
        <li>Item @counter</li>
        counter++;
    }
</ul>

4. The do-while Loop

The do-while loop executes at least once before checking the condition.

Example: Executing a Block at Least Once

@{
    int counter = 0;
}
<ul>
    @do
    {
        <li>Item @counter</li>
        counter++;
    } while (counter < 3);
</ul>

Combining Arrays and Loops

Arrays and loops often go hand-in-hand in Razor to process collections of data dynamically.

Example: Displaying Names with a Loop

@{
    string[] names = { "Alice", "Bob", "Charlie" };
}
<ul>
    @foreach (var name in names)
    {
        <li>Hello, @name!</li>
    }
</ul>

Example: Adding Conditions in Loops

@{
    string[] fruits = { "Apple", "Banana", "Cherry" };
}
<ul>
    @foreach (var fruit in fruits)
    {
        if (fruit == "Banana")
        {
            <li>@fruit (My Favorite!)</li>
        }
        else
        {
            <li>@fruit</li>
        }
    }
</ul>

Advanced Techniques

1. Nesting Loops

You can use loops inside other loops to work with multidimensional arrays.

Example: Multidimensional Array

@{
    string[,] products = {
        { "Laptop", "Electronics" },
        { "Shirt", "Clothing" },
        { "Apple", "Fruits" }
    };
}
<ul>
    @for (int i = 0; i < products.GetLength(0); i++)
    {
        <li>@products[i, 0] - @products[i, 1]</li>
    }
</ul>

2. Skipping Iterations

You can use continue to skip specific iterations and break to exit a loop.

Example: Skipping Specific Items

@{
    string[] items = { "Item1", "SkipMe", "Item2" };
}
<ul>
    @foreach (var item in items)
    {
        if (item == "SkipMe")
        {
            continue;
        }
        <li>@item</li>
    }
</ul>

Best Practices for Loops and Arrays in Razor

  1. Avoid Hardcoding
    Use dynamic data sources such as databases or APIs.
  2. Optimize Performance
    Avoid nesting multiple loops unnecessarily for large datasets.
  3. Keep It Readable
    Use meaningful variable names and comments to describe complex logic.
  4. Handle Exceptions
    Always check for null or empty arrays before iterating through them.

Common Mistakes and How to Avoid Them

  1. Index Out of Range
    Always validate the array index in a for loop.
  2. Null Reference Exceptions
    Ensure arrays are initialized before using them.
  3. Infinite Loops
    Double-check loop conditions, especially in while and do-while.

Why Master Loops and Arrays in Razor?

Loops and arrays are essential for building dynamic web pages. By mastering them, you can create efficient and responsive applications, improving both performance and user experience.

Learn More at The Coding College

At The Coding College, we aim to simplify coding concepts and empower you to build better web applications. Dive into our ASP.NET Razor tutorials for more insights and examples.

Have questions or need further assistance with Razor loops and arrays? Drop your queries below or explore our in-depth guides at The Coding College.

Leave a Comment