0
0
CsharpHow-ToBeginner · 3 min read

How to Iterate Over List in C#: Simple Syntax and Examples

In C#, you can iterate over a list using a foreach loop to access each item easily or a for loop to use indexes. The foreach loop is simple and safe for reading items, while the for loop gives more control when you need the index.
📐

Syntax

There are two common ways to iterate over a list in C#:

  • foreach loop: Automatically goes through each item in the list.
  • for loop: Uses an index to access each item by position.

Use foreach when you only need to read items. Use for when you need the index or want to modify items.

csharp
List<string> items = new List<string> { "apple", "banana", "cherry" };

// foreach loop
foreach (string item in items)
{
    Console.WriteLine(item);
}

// for loop
for (int i = 0; i < items.Count; i++)
{
    Console.WriteLine(items[i]);
}
💻

Example

This example shows how to print all items in a list using both foreach and for loops.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> fruits = new List<string> { "apple", "banana", "cherry" };

        Console.WriteLine("Using foreach loop:");
        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }

        Console.WriteLine("Using for loop:");
        for (int i = 0; i < fruits.Count; i++)
        {
            Console.WriteLine(fruits[i]);
        }
    }
}
Output
Using foreach loop: apple banana cherry Using for loop: apple banana cherry
⚠️

Common Pitfalls

Common mistakes when iterating over lists include:

  • Modifying the list inside a foreach loop, which causes errors.
  • Using wrong loop conditions in for loops, like i <= list.Count instead of i < list.Count, causing out-of-range errors.
  • Confusing the item variable with the index in foreach loops (there is no index).

Always use for if you need to modify the list or access indexes.

csharp
List<int> numbers = new List<int> {1, 2, 3};

// Wrong: modifying list inside foreach (throws error)
// foreach (int n in numbers)
// {
//     numbers.Remove(n);
// }

// Right: use for loop to modify safely
for (int i = numbers.Count - 1; i >= 0; i--)
{
    numbers.RemoveAt(i);
}
📊

Quick Reference

Here is a quick summary of how to iterate over a list in C#:

MethodUsageWhen to Use
foreachfor each item in listReading items, simple iteration
forfor (int i = 0; i < list.Count; i++)When index needed or modifying list
List.ForEach(Action)list.ForEach(item => ...)Quick action on each item (read-only)

Key Takeaways

Use foreach loop for simple, safe iteration over list items.
Use for loop when you need the index or want to modify the list.
Never modify a list inside a foreach loop to avoid runtime errors.
Always check loop conditions carefully to prevent out-of-range errors.
List.ForEach method is a concise alternative for read-only actions on items.