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.
List<T> and Dictionary<TKey, TValue>.
List<T>
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 + " ");4 F1 True F1, B1, C1, C2 B1 C1 C2 F1
| Member | Does |
|---|---|
Add(x), AddRange(xs) | |
Insert(i, x) | |
Remove(x), RemoveAt(i), Clear() | |
Count | Length) |
list[i] | |
Contains, IndexOf, Find, Exists | |
Sort(), Reverse() | |
ToArray() |
Dictionary<TKey, TValue>
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}");IPE200: 22.4 kg/m False IPE200 = 22.4 IPE300 = 42.3 HEA200 = 42.3
A classic: counting things
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}");IPE200: 3 HEA200: 1 IPE300: 1
Which one?
| Need | Use | Lookup speed |
|---|---|---|
List<T> | ||
Dictionary<K, V> | ||
T[] |
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
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)}");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 TryGetValueinstead ofdict[key]when a key may be missing.Don’t modify a collection while iterating over it with foreach.