<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Working with data
All lessons in this course

Lesson 31 of 60 15 minIntermediate

Collections: List and Dictionary

The two collections you will use every day: List<T> for ordered items that grow and shrink, Dictionary<TKey, TValue> for fast lookups by key.

Arrays have a fixed size. Real data grows: members get added to a model, rows get loaded from a file. .NET’s collections handle that for you. The two most important are List<T> and Dictionary<TKey, TValue>.

Interactive

Inside List and Dictionary

B10
B21
C12
3

Count = 3 · Capacity = 4(grey slots are reserved but empty; when full, the list allocates double the space and copies the items across)

var list = new List<string>();Try Add a few times and watch Capacity jump from 4 to 8.

List<T>

List.cs
var marks = new List<string> { "B1", "B2" };   // collection initialisermarks.Add("C1");marks.AddRange(new[] { "C2", "BR1" });marks.Insert(0, "F1");marks.Remove("B2");                // first matchmarks.RemoveAt(marks.Count - 1);   // last item Console.WriteLine(marks.Count);Console.WriteLine(marks[0]);Console.WriteLine(marks.Contains("C1"));Console.WriteLine(string.Join(", ", marks)); marks.Sort();foreach (string m in marks) Console.Write(m + " ");
Output
4
F1
True
F1, B1, C1, C2
B1 C1 C2 F1
MemberDoes
Add(x), AddRange(xs)append at the end
Insert(i, x)insert at index (shifts later items)
Remove(x), RemoveAt(i), Clear()remove items
Countnumber of items (arrays use Length)
list[i]read or replace by index
Contains, IndexOf, Find, Existssearch (checks items one by one)
Sort(), Reverse()reorder in place
ToArray()copy to an array

Dictionary<TKey, TValue>

A dictionary stores key → value pairs, like a phone book. Looking up by key is almost instant, no matter how many entries there are, because the key’s hash code points straight to its bucket.

Dictionary.cs
var kgPerMetre = new Dictionary<string, double>{    ["IPE200"] = 22.4,    ["IPE300"] = 42.2};kgPerMetre.Add("HEA200", 42.3);         // Add throws if the key existskgPerMetre["IPE300"] = 42.3;            // indexer: add or replace if (kgPerMetre.TryGetValue("IPE200", out double kg))    Console.WriteLine($"IPE200: {kg} kg/m"); Console.WriteLine(kgPerMetre.ContainsKey("UB305")); foreach (var (profile, w) in kgPerMetre)       // KeyValuePair deconstruction    Console.WriteLine($"{profile} = {w}");
Output
IPE200: 22.4 kg/m
False
IPE200 = 22.4
IPE300 = 42.3
HEA200 = 42.3

A classic: counting things

Count.cs
string[] profiles = { "IPE200", "HEA200", "IPE200", "IPE300", "IPE200" };var counts = new Dictionary<string, int>(); foreach (string p in profiles){    counts.TryGetValue(p, out int n);   // n is 0 if missing    counts[p] = n + 1;}foreach (var (p, n) in counts) Console.WriteLine($"{p}: {n}");
Output
IPE200: 3
HEA200: 1
IPE300: 1

Which one?

NeedUseLookup speed
Ordered items, access by positionList<T>by index: O(1); by value: O(n)
Find a value by a unique keyDictionary<K, V>by key: O(1)
Fixed size, maximum speedarray T[]by index: O(1)

O(1) means “constant time”: the same speed with 10 or 10 million items. O(n) means the time grows with the number of items. Choosing a Dictionary instead of searching a List is one of the easiest big performance wins.

Quick check

What happens with dict.Add("A", 1) when "A" is already a key?

Quick check

For 1 million items, which finds an item fastest?

Practice

Given a list of words, build a Dictionary<char, List<string>> that groups the words by their first letter, then print each letter with its words. Use { "beam", "bolt", "column", "brace", "cleat" }.

Show the solution
Solution.cs
var words = new List<string> { "beam", "bolt", "column", "brace", "cleat" };var groups = new Dictionary<char, List<string>>(); foreach (string w in words){    char first = w[0];    if (!groups.TryGetValue(first, out var list))    {        list = new List<string>();        groups[first] = list;    }    list.Add(w);} foreach (var (letter, list) in groups)    Console.WriteLine($"{letter}: {string.Join(", ", list)}");
Output
b: beam, bolt, brace
c: column, cleat

Remember

  • List<T> is a resizable array: Add, Insert, Remove, Count, [i].
  • Dictionary<K, V> maps unique keys to values with O(1) lookups.
  • Use TryGetValue instead of dict[key] when a key may be missing.
  • Don’t modify a collection while iterating over it with foreach.
0 of 60 lessons completed