C#C# · Lesson 5 of 9

Collections

C# has a rich set of collection types in System.Collections.Generic. List<T> is your workhorse.

C#
using System.Collections.Generic;

// List<T> — dynamic array
List<string> fruits = new() { "apple", "banana", "cherry" };
fruits.Add("date");
fruits.Remove("banana");
fruits.Insert(0, "avocado");
Console.WriteLine(fruits.Count);       // 4
Console.WriteLine(fruits.Contains("apple")); // True
fruits.Sort();
Console.WriteLine(string.Join(", ", fruits)); // apple, avocado, cherry, date

// Dictionary<TKey, TValue>
Dictionary<string, int> scores = new() {
    ["Alice"] = 95,
    ["Bob"] = 87,
};
scores["Carol"] = 92;
scores["Alice"] = 98;  // update

if (scores.TryGetValue("Dave", out int daveScore)) {
    Console.WriteLine(daveScore);
} else {
    Console.WriteLine("Dave not found");
}

foreach (var (name, score) in scores) {
    Console.WriteLine($"{name}: {score}");
}

// HashSet<T> — unique values
HashSet<int> set = new() { 1, 2, 3, 2, 1 };  // duplicates removed
Console.WriteLine(set.Count);  // 3

// Queue<T> and Stack<T>
Queue<string> queue = new();
queue.Enqueue("first");
queue.Enqueue("second");
Console.WriteLine(queue.Dequeue());  // first

Stack<int> stack = new();
stack.Push(1); stack.Push(2); stack.Push(3);
Console.WriteLine(stack.Pop());  // 3 (LIFO)
◆ Note
new() — called "target-typed new expression" (C# 9+) — infers the type from the variable declaration. List<string> fruits = new(); is cleaner than List<string> fruits = new List<string>();