Loop through a List in C#
This post will discuss how to loop through a List in C#.
1. Using foreach Statement
The standard option to iterate over the List in C# is using a foreach loop. Then, we can perform any action on each element of the List. The following code example demonstrates its usage by displaying the contents of the list to the console.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; foreach (var i in nums) { Console.WriteLine(i); } } } |
Output:
1
2
3
4
5
2. Using List<T>.ForEach
Another good alternative to iterate through a list is using List<T>.ForEach(Action<T>) method. It performs the specified action on each element of the list. It accepts a delegate to perform on each element of the List. The following example shows how to print the contents of a list using the Action<T> delegate.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; nums.ForEach(i => Console.WriteLine(i)); } } |
Output:
1
2
3
4
5
3. Using For Loop
Finally, we can replace a foreach loop with an index-based for-loop, as the following example illustrates.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; for (var i = 0; i < nums.Count; i++) { Console.WriteLine(nums[i]); } } } |
Output:
1
2
3
4
5
That’s all about looping through a List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)