C# How To Loop Through a List
Loop Through a List
Use a foreach loop to go through all the items in a List:
Example
List<string> cars = new List<string> { "Volvo", "BMW", "Ford", "Mazda" };
foreach (string car in cars)
{
Console.WriteLine(car);
}
If you also need the index of each item, use a for loop with the Count property:
Example
List<string> cars = new List<string> { "Volvo", "BMW", "Ford", "Mazda" };
for (int i = 0; i < cars.Count; i++)
{
Console.WriteLine(i + ": " + cars[i]);
}
Explanation:
The foreach loop gives you each item, one by one.
The for loop uses i as the index, from 0 up to cars.Count - 1. A list uses Count, not Length like an array.