Skip to content

Lists and foreach

The Course
•
25 min study

Variables hold one value. A collection holds many. List<int> is a list of integers, and List<string> a list of strings; the type in angle brackets says what the list may contain. Unlike an array, a list can grow and shrink.

Making and changing a list

Add puts a value at the end. Count is how many values are in the list. (An array calls this Length, and a list calls it Count.) [0] reads the first item, because indexes start at 0. Remove removes the first matching value, and RemoveAt removes by position.

Trace the list after each change C#
var minutes = new List<int> { 25, 10 };
minutes.Add(40);
Console.WriteLine(minutes.Count);
Console.WriteLine(minutes[0]);

minutes[0] = 30;
minutes.Remove(10);
Console.WriteLine(string.Join(", ", minutes));

Console.WriteLine(minutes.Contains(40));
Check your prediction
Text
3
25
30, 40
True

The valid indexes run from 0 to Count - 1. Reading minutes[Count] compiles, then crashes while the program runs.

One past the end C#
var topics = new List<string> { "Loops", "Lists" };
Console.WriteLine(topics[1]);
Console.WriteLine(topics[topics.Count]);
Check your prediction
Text
Lists
Unhandled exception. System.ArgumentOutOfRangeException

Going through a list

foreach visits each item in turn and saves you from handling indexes at all. This is why the off-by-one worries of for mostly disappear. Use foreach when you want every item, and a for loop when you need the position.

foreach, and for when you need the position C#
var minutes = new List<int> { 25, 0, 40 };

int total = 0;
foreach (int value in minutes)
{
    total += value;
}
Console.WriteLine(total);

for (int i = 0; i < minutes.Count; i++)
{
    Console.WriteLine($"{i + 1}. {minutes[i]}");
}
Check your prediction
Text
65
1. 25
2. 0
3. 40

The loop variable in foreach is a copy for that pass, and the compiler won't let you assign to it. You also can't add or remove items in a list while foreach is going through it. That's an exception at run time, because the loop would lose its place.

Passing a list to a method

A method can take a list as a parameter, just like any other value. Day 5 explains exactly why a change that a method makes to a list stays visible afterwards. For now, write methods that only read the list, and return an answer.

An empty list is an important case. A correct foreach loop handles it without any special code, as the loop simply runs zero times. Division by the Count does need a guard.

Methods over a list C#
var sessions = new List<int> { 25, 40, 10 };
var empty = new List<int>();

Console.WriteLine(Longest(sessions));
Console.WriteLine(Longest(empty));

static int Longest(List<int> values)
{
    int longest = 0;
    foreach (int value in values)
    {
        if (value > longest)
        {
            longest = value;
        }
    }
    return longest;
}
Check your prediction
Text
40
0

Going further: LINQ

LINQ is a set of ready-made operations on collections. You pass small inline functions called lambdas, written x => ..., meaning "given x, produce this". The loops you've written are still worth understanding, because that's what these methods do for you.

The same answers, shorter C#
var minutes = new List<int> { 25, 0, 40 };

Console.WriteLine(minutes.Sum());
Console.WriteLine(minutes.Max());
Console.WriteLine(minutes.Count(value => value > 0));
Console.WriteLine(string.Join(",", minutes.Where(value => value > 20)));
Check your prediction
Text
65
40
2
25,40

minutes.Count without parentheses is the list's property: how many items it holds, here 3. minutes.Count(value => value > 0) is a LINQ method with the same name that counts only the items the lambda accepts, here 2.

Your turn

Exercise

Count the real sessions

Write Summarize(List<int> minutes), which goes through the list with foreach and ignores any value below 1. It should return the text 2 sessions, 65 minutes for the list 25, 0, 40, -3. Print that, and print the result for an empty list. Don't use LINQ here.

Your workspace C#
var minutes = new List<int> { 25, 0, 40, -3 };
Console.WriteLine(minutes.Count);
Hint 1: the idea

Keep two running values, a count and a total. Skip invalid values before updating either one.

Hint 2: a first step

Write the method with the parameter List<int> minutes, and return only the total at first.

Show one solution
C#
Console.WriteLine(Summarize(new List<int> { 25, 0, 40, -3 }));
Console.WriteLine(Summarize(new List<int>()));

static string Summarize(List<int> minutes)
{
    int sessions = 0;
    int total = 0;
    foreach (int value in minutes)
    {
        if (value < 1)
        {
            continue;
        }
        sessions++;
        total += value;
    }
    return $"{sessions} sessions, {total} minutes";
}
Text
2 sessions, 65 minutes
0 sessions, 0 minutes

continue skips the rest of the loop body for a bad value, so the normal case below it stays unindented and easy to read. Nesting the counting inside if (value >= 1) would work too; with more checks, though, each would add another level, while each continue is one flat line. An empty list never enters the loop, so it gives 0 and 0 with no special case.

A list with one session prints 1 sessions. Fix the wording with the conditional operator, and add a test case to show it works.

Was this article helpful?

Your response is saved on this device.