Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to iterate over a C# list?
A List in C# is a generic collection that stores elements of the same type. There are several ways to iterate over a C# list, each with its own advantages depending on your specific needs.
Syntax
Following is the basic syntax for declaring and initializing a list −
List<T> listName = new List<T>();
Following are the common iteration syntaxes −
// foreach loop
foreach(var item in list) {
// process item
}
// for loop
for(int i = 0; i < list.Count; i++) {
// process list[i]
}
Using foreach Loop
The foreach loop is the most common and readable way to iterate over a list. It automatically handles the iteration without requiring index management −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
var products = new List<string>();
products.Add("Belts");
products.Add("T-Shirt");
products.Add("Trousers");
Console.WriteLine("Our list....");
foreach(var p in products) {
Console.WriteLine(p);
}
}
}
The output of the above code is −
Our list.... Belts T-Shirt Trousers
Using for Loop with Index
When you need access to the index of each element, use a traditional for loop −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
var numbers = new List<int> {10, 20, 30, 40, 50};
Console.WriteLine("List with indexes:");
for(int i = 0; i < numbers.Count; i++) {
Console.WriteLine("Index " + i + ": " + numbers[i]);
}
}
}
The output of the above code is −
List with indexes: Index 0: 10 Index 1: 20 Index 2: 30 Index 3: 40 Index 4: 50
Using while Loop
A while loop can also be used for iteration, though it's less common −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
var colors = new List<string> {"Red", "Green", "Blue"};
int index = 0;
Console.WriteLine("Colors using while loop:");
while(index < colors.Count) {
Console.WriteLine(colors[index]);
index++;
}
}
}
The output of the above code is −
Colors using while loop: Red Green Blue
Comparison of Iteration Methods
| Method | Best Used When | Advantages |
|---|---|---|
| foreach | Simple iteration over all elements | Clean syntax, no index management needed |
| for loop | Need access to index or specific range | Full control over iteration, can modify list |
| while loop | Complex iteration conditions | Maximum flexibility for custom logic |
Conclusion
The foreach loop is the preferred method for simple list iteration in C# due to its clean syntax and safety. Use for loops when you need index access, and while loops for more complex iteration scenarios.
