2.4.8 Traversing a List With foreach

Video: Using Loops to Work With Lists (9:23)
Traversing a List With foreach

The coach wants to read every score in the current sequence. A foreach loop supplies each list item in index order without a manually managed index.

Explore the idea
Read each current value

Use using System.Collections.Generic; at the top of the C# file, before its class definitions. Place the following statements inside an existing method.

Visit scores in order
List<int> roundGoals = new List<int>();
roundGoals.Add(2);
roundGoals.Add(0);
roundGoals.Add(3);
int roundsVisited = 0;

foreach (int goals in roundGoals)
{
    roundsVisited = roundsVisited + 1;
}

The iteration variable goals receives 2, then 0, then 3. The body runs three times, even though one score is zero. The counter finishes at 3.

Traversal order
Next item available? Value supplied roundsVisited after body
Yes 2 1
Yes 0 2
Yes 3 3
No No value supplied 3; body skipped
Keep traversal stable

For an int list, the iteration variable supplies a value and cannot be assigned a new value inside the loop. A Player iteration variable can reach and update a Player field; changing that object’s field does not add or remove list entries.

Predict and check