C# Programming Tutorial 0/45 lessons ~6 min read Lesson 9

    Loops

    Loops repeat work: for with counters, foreach over collections, while for unknown iterations, and do-while for at-least-once execution.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Loops repeat work: for with counters, foreach over collections, while for unknown iterations, and do-while for at-least-once execution. Choosing the right loop affects readability and performance — foreach on List uses struct enumerator without boxing in modern .NET.

    In production code, LINQ often replaces explicit loops for transformations, but interviews still ask you to reverse arrays, detect cycles, and analyze complexity. Async streams use await foreach for IAsyncEnumerable.

    This lesson covers every loop form, IEnumerable iteration, and when to prefer LINQ over manual for.

    The story

    An accounting dashboard sums all positive transactions for a monthly report and generates human-readable statement lines like 2026-03-15: $1,250.00 for each entry. Some months have dozens of transactions; others have thousands — loops process them one at a time without hand-writing repetitive code.

    Both indexed for loops and foreach with yield return appear in production ETL pipelines that transform bank ledgers into PDF statements.

    Understanding the topic

    Key concepts

    • for(init; condition; increment) — index-based iteration.
    • foreach iterates IEnumerable — cannot assign to loop variable.
    • while checks condition before body; do-while after.
    • Collections implement GetEnumerator for foreach.
    • await foreach for async sequences (IAsyncEnumerable).
    • LINQ replaces many loops with declarative Where/Select.
    text
    flowchart TD
    Init[Initialize] --> Cond{Condition?}
    Cond -->|true| Body[Loop Body]
    Body --> Update[Increment]
    Update --> Cond
    Cond -->|false| Exit([Exit Loop])

    Step-by-step explanation

    1. for: initialize counter, test, execute, increment.
    2. foreach: compiler generates enumerator try/finally Dispose.
    3. while: repeat until condition false — watch infinite loops.
    4. Nested loops multiply complexity — O(n²) matrix operations.
    5. break exits loop; continue skips to next iteration.
    6. Prefer Span or for with index when performance critical.

    Practical code example

    Aggregate monthly transactions with foreach and for index access:

    csharp
    namespace TechLearningPro.Loops;
    public record Transaction(DateOnly Date, decimal Amount);
    public static class MonthlyAggregator
    {
    public static decimal SumPositive(IReadOnlyList<Transaction> txns)
    {
    decimal total = 0m;
    for (var i = 0; i < txns.Count; i++)
    {
    var txn = txns[i];
    if (txn.Amount > 0)
    total += txn.Amount;
    }
    return total;
    }
    public static IEnumerable<string> FormatStatements(IEnumerable<Transaction> txns)
    {
    foreach (var t in txns)
    yield return
    quot;{t.Date:yyyy-MM-dd}: {t.Amount:C}";
    }
    }

    Line-by-line code explanation

    • public record Transaction(DateOnly Date, decimal Amount) models a single ledger entry.
    • SumPositive(IReadOnlyList<Transaction> txns) accepts a read-only list for efficient indexed access.
    • decimal total = 0m initializes an accumulator before the loop starts.
    • for (var i = 0; i < txns.Count; i++) walks the list by index — good when you need position.
    • var txn = txns[i] reads the current transaction inside the loop body.
    • if (txn.Amount > 0) filters out refunds and chargebacks from the positive total.
    • total += txn.Amount adds qualifying amounts to the running sum.
    • FormatStatements(IEnumerable<Transaction> txns) returns lazy formatted lines for large datasets.
    • foreach (var t in txns) iterates each transaction without managing an index manually.
    • yield return $"{t.Date:yyyy-MM-dd}: {t.Amount:C}" produces one formatted line at a time without building a full list upfront.

    Key takeaway: for with index on IReadOnlyList avoids double enumeration. yield return implements iterator without manual state machine.

    Real-world use

    Where you'll use this in production

    • Batch processing ledger entries in nightly jobs.
    • Polling retry loops with exponential backoff.
    • Desktop UI refreshing list views from ObservableCollection.
    • ETL pipelines reading CSV rows until EOF.

    Best practices

    • Use foreach for readability unless index needed.
    • Avoid modifying collection during foreach — InvalidOperationException.
    • Extract loop body to methods when >5 lines.
    • Consider LINQ for transformations; loops for hot paths.
    • Use CancellationToken in long-running while loops.

    Common mistakes

    • Off-by-one errors in for boundary conditions.
    • Infinite while(true) without break or cancellation.
    • Modifying foreach collection — use for reverse or ToList copy.
    • Nested loops without considering algorithmic complexity.

    Advanced interview questions

    Q1Beginnerforeach vs for?
    foreach simpler for collections; for when index or reverse iteration needed.
    Q2BeginnerCan you modify loop variable in foreach?
    No — compile error; iteration variable is read-only.
    Q3IntermediateWhat is IAsyncEnumerable?
    Async sequence consumed with await foreach for streaming data.
    Q4IntermediateWhen LINQ over loop?
    LINQ for clarity and composability; loops for micro-optimization or complex control flow.
    Q5AdvancedImplement paginated API fetch until no more pages without loading all into memory.
    while loop with page token; await HttpClient; yield return or process stream; respect CancellationToken.

    Summary

    for, foreach, while, do-while cover all iteration needs. foreach uses IEnumerator; await foreach for async streams. LINQ often replaces manual loops for data transforms. Watch off-by-one and collection modification pitfalls. Next: break, continue, and loop control flow.

    Ready to mark this lesson complete?Track your journey across the entire course.