Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson10 / 20

    Module 3 · Collections and objects: organise your data · Lesson 10 of 20

    Grow a task collection with List

    A learner adds another task after the plan is created. What should grow? Use a list, then inspect what changes after adding and removing items.

    Predict the changing task list

    An array has a fixed length. A List<string> is useful when tasks will be added or removed. The angle-bracket part tells C# that this list holds strings; List<int> would hold integers. using System.Collections.Generic; makes the List type name available.

    Predict every output line before running this complete program.

    Read the list-creation syntax before running: new List<string> { ... } creates a list with the initial strings written between the braces. new List<int>() creates an empty list of integers; use Add to put values in it. Here new means create an instance, and <string> or <int> selects the element type.

    C#
    using System;
    using System.Collections.Generic;
    
    List<string> tasks = new List<string> { "Read", "Practise" };
    tasks.Add("Review");
    bool removed = tasks.Remove("Read");
    
    Console.WriteLine(removed);
    Console.WriteLine($"Count: {tasks.Count}");
    
    foreach (string task in tasks)
    {
        Console.WriteLine(task);
    }

    What is the list count after Add and Remove in this program?

    A 1
    B 2
    C 3
    D 4
    Show answer

    Correct answer: B

    The list begins with two items, Add makes three, and a successful Remove makes two.

    Option A: Only one of the three items is removed.

    Option C: This ignores the successful removal.

    Option D: Only one item was added, not two.

    Hint: Write the count after each operation: 2 → ? → ?.

    Trace membership

    OperationItems in orderCount
    CreateRead, Practise2
    Add ReviewRead, Practise, Review3
    Remove ReadPractise, Review2

    Add appends an item. Remove searches for the supplied value, removes its first matching occurrence, and returns whether it found one. That bool result lets your program report a useful message when a requested task does not exist.

    A list uses Count for its current number of elements. If you access an item by index, valid positions are 0 through Count - 1. Check Count before reading a position that might not exist. Prefer foreach when you simply want to display all items, including when the list might be empty.

    Growing means the list can change its membership; it does not mean every index is valid. Add first, then read a position that exists. A list containing two tasks still has no item at index 2.

    If tasks.Remove("Missing") cannot find that text, what happens?

    A It returns False and keeps the items unchanged
    B It removes the last task
    C It creates a new task named Missing
    D It returns True and clears the list
    Show answer

    Correct answer: A

    Remove reports False when no matching item is found; this does not change membership.

    Option B: Remove uses the supplied value, not the last position.

    Option C: Adding a task requires Add.

    Option D: Remove does not clear the list when a value is missing.

    Filter into a separate result

    Do not add or remove list items while a foreach loop is traversing that same list. Such changes invalidate the traversal and can cause an exception. A simple beginner approach is to leave the source list alone and put the values you want into a new list.

    C#
    using System;
    using System.Collections.Generic;
    
    List<int> recordedMinutes = new List<int> { 15, 0, 20, 0, 10 };
    List<int> positiveMinutes = new List<int>();
    
    foreach (int minutes in recordedMinutes)
    {
        if (minutes > 0)
        {
            positiveMinutes.Add(minutes);
        }
    }
    
    foreach (int minutes in positiveMinutes)
    {
        Console.WriteLine(minutes);
    }

    Why is Add safe in the first foreach loop of this filter?

    A List never checks changes during a loop
    B The loop has only five items
    C It reads recordedMinutes but adds to a different list
    D The if statement disables list rules
    Show answer

    Correct answer: C

    The list being traversed is unchanged. Add targets the separate positiveMinutes list.

    Option A: Changing the list being traversed can invalidate its enumerator.

    Option B: A small collection has the same traversal rule.

    Option D: An if statement does not change the collection’s rules.

    Hint: Compare the name after in with the name before Add.

    Try it independently

    Start with Read, Read and Review. Remove Read once, then display numbered tasks. Predict two remaining tasks: Read and Review. Removing by value removes the first occurrence only. Use index + 1 for the displayed human number while keeping the actual index zero-based.

    C#
    using System;
    using System.Collections.Generic;
    
    List<string> tasks = new List<string> { "Read", "Read", "Review" };
    tasks.Remove("Read");
    
    for (int index = 0; index < tasks.Count; index++)
    {
        Console.WriteLine($"{index + 1}. {tasks[index]}");
    }

    Explain back

    Explain why a task editor is a good use for List rather than a fixed-length array. Then explain the difference between a zero-based index and the number shown to a person. Finally, describe how the filter avoids changing the list it is traversing.

    References: Microsoft — List.Remove and list traversal rules.

    Quick reference

    • List<T> holds values of the chosen element type.
    • Add appends an item.
    • Remove removes the first matching value and returns a bool.
    • Count is the current number of elements.
    • Valid indexes satisfy 0 <= index and index < Count.
    • During foreach, leave the traversed list unchanged; build a separate result when filtering.
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·