List is a collection of items. We can use a foreach loop to loop through its items. The code snippet in Listing 6 reads all items of a List and displays on the console.
Foreach-loop. This is the best loop when no index is needed. We use the “foreach” keyword and declare a variable (like “prime” here) that is assigned to each element as we pass over it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(2); list.Add(3); list.Add(7); // Loop through List with foreach. foreach (int prime in list) { System.Console.WriteLine(prime); } } } |
For-loop. Sometimes we want to access indexes of a List as we loop over its elements. A for-loop is ideal here. We print each element index with a string interpolation expression.
Tip: Arrays use Length. But Lists use Count. To loop backwards, start with list.Count – 1, and decrement to >= 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(new int[]{ 2, 3, 7 }); // Loop with for and use string interpolation to print values. for (int i = 0; i < list.Count; i++) { Console.WriteLine($"{i} = {list[i]}"); } } } |