Collections & LINQ · Lesson 3

Walking items

foreach visits every item once, in order.

How it works

The body runs for 2, then for 2, then for 2. total starts at 0 and becomes 2, then 4, then 6. Sum does the same walk and also prints 6. The loop variable price is one item at a time, not the whole array.

A working example

var prices = new[] { 2m, 2m, 2m };
var total = 0m;
foreach (var price in prices)
{
    total = total + price;
}
Console.WriteLine(total);

Expected output

6
Try this
Three visits, one total.