C# Collections
Arrays have a fixed size. Real programs need containers that grow and shrink, look things up by key, ignore duplicates or process items in order of arrival. The System.Collections.Generic namespace provides a type-safe collection for each of these jobs.
| Collection | Think of it as | Key operations |
|---|---|---|
List<T> |
A resizable array | Add, Remove, Insert, index [i] |
Dictionary<TKey, TValue> |
A lookup table | [key], TryGetValue, ContainsKey |
HashSet<T> |
A bag of unique values | Add, Contains, set operations |
Queue<T> |
A waiting line (first in, first out) | Enqueue, Dequeue, Peek |
Stack<T> |
A pile of plates (last in, first out) | Push, Pop, Peek |
List<T>
List<T> is the workhorse collection. It keeps elements in order, grows automatically and allows access by index.
using System;
using System.Collections.Generic;
var tasks = new List<string> { "write report", "email Bob" };
tasks.Add("book flights");
tasks.Insert(0, "coffee");
Console.WriteLine(quot;{tasks.Count} tasks: {string.Join(" | ", tasks)}");
tasks.Remove("email Bob");
tasks.RemoveAt(0);
Console.WriteLine(string.Join(" | ", tasks));
Console.WriteLine(tasks.Contains("book flights"));
Console.WriteLine(tasks.IndexOf("write report"));
Console.WriteLine(tasks[1]);
var numbers = new List<int> { 5, 3, 9, 1 };
numbers.Sort();
numbers.Reverse();
Console.WriteLine(string.Join(", ", numbers));
numbers.RemoveAll(n => n < 4);
Console.WriteLine(string.Join(", ", numbers));4 tasks: coffee | write report | email Bob | book flights
write report | book flights
True
0
book flights
9, 5, 3, 1
9, 5
Dictionary<TKey, TValue>
A dictionary maps unique keys to values and finds a value by key almost instantly, no matter how many entries it holds.
using System;
using System.Collections.Generic;
var capitals = new Dictionary<string, string>
{
["France"] = "Paris",
["Japan"] = "Tokyo",
};
capitals.Add("Peru", "Lima");
capitals["Japan"] = "Tōkyō"; // overwrite existing key
Console.WriteLine(capitals["France"]);
Console.WriteLine(capitals.ContainsKey("Chile"));
if (capitals.TryGetValue("Peru", out string city))
Console.WriteLine(quot;Peru -> {city}");
foreach (var (country, capital) in capitals)
Console.WriteLine(quot;{country}: {capital}");
// Counting words is a classic dictionary job
string text = "the cat and the hat and the bat";
var counts = new Dictionary<string, int>();
foreach (string word in text.Split(' '))
counts[word] = counts.GetValueOrDefault(word) + 1;
Console.WriteLine(quot;'the' appears {counts["the"]} times, {counts.Count} distinct words");Paris
False
Peru -> Lima
France: Paris
Japan: Tōkyō
Peru: Lima
'the' appears 3 times, 5 distinct words
Reading a missing key with dict[key] throws a KeyNotFoundException; TryGetValue and GetValueOrDefault are the safe alternatives. Add throws if the key already exists, whereas the indexer dict[key] = value adds or overwrites.
Note:
Dictionarydoes not promise any particular iteration order. In practice, entries come back in insertion order as long as you never remove anything — but don't rely on it. UseSortedDictionarywhen you need sorted keys.
HashSet<T>
A HashSet<T> stores each value at most once and answers "is this in the set?" very quickly. It also supports mathematical set operations.
using System;
using System.Collections.Generic;
var visited = new HashSet<string>();
string[] clicks = { "home", "shop", "home", "cart", "shop", "home" };
foreach (string page in clicks)
{
bool isNew = visited.Add(page); // false if already present
Console.WriteLine(quot;{page,-5} new={isNew}");
}
Console.WriteLine(quot;Unique pages: {visited.Count}");
var alice = new HashSet<string> { "chess", "hiking", "jazz" };
var bob = new HashSet<string> { "jazz", "cooking", "chess" };
var common = new HashSet<string>(alice);
common.IntersectWith(bob);
Console.WriteLine(quot;Shared hobbies: {string.Join(", ", common)}");
Console.WriteLine(alice.Overlaps(bob));home new=True
shop new=True
home new=False
cart new=True
shop new=False
home new=False
Unique pages: 3
Shared hobbies: chess, jazz
True
Other set operations: UnionWith, ExceptWith, IsSubsetOf, SetEquals.
Queue<T> and Stack<T>
A queue hands items out in the order they arrived (FIFO) — print jobs, customer support tickets, breadth-first search. A stack hands out the most recently added item first (LIFO) — undo history, matching brackets, depth-first search.
using System;
using System.Collections.Generic;
var line = new Queue<string>();
line.Enqueue("Ann");
line.Enqueue("Ben");
line.Enqueue("Cleo");
Console.WriteLine(quot;Next up: {line.Peek()}");
while (line.Count > 0)
Console.WriteLine(quot;Serving {line.Dequeue()}");
var undo = new Stack<string>();
undo.Push("type 'Hello'");
undo.Push("bold text");
undo.Push("insert image");
Console.WriteLine(quot;Undo: {undo.Pop()}");
Console.WriteLine(quot;Undo: {undo.Pop()}");
Console.WriteLine(quot;Remaining: {undo.Count}, top is '{undo.Peek()}'");Next up: Ann
Serving Ann
Serving Ben
Serving Cleo
Undo: insert image
Undo: bold text
Remaining: 1, top is 'type 'Hello''
A stack makes checking balanced brackets almost trivial:
using System;
using System.Collections.Generic;
static bool IsBalanced(string s)
{
var open = new Stack<char>();
foreach (char c in s)
{
if (c is '(' or '[' or '{') open.Push(c);
else if (c is ')' or ']' or '}')
{
if (open.Count == 0) return false;
char o = open.Pop();
if ((o, c) is not (('(', ')') or ('[', ']') or ('{', '}'))) return false;
}
}
return open.Count == 0;
}
foreach (string s in new[] { "(a[b]{c})", "(]", "((x)", "{[()()]}" })
Console.WriteLine(quot;{s,-10} {IsBalanced(s)}");(a[b]{c}) True
(] False
((x) False
{[()()]} True
Choosing a collection
| You need to… | Use |
|---|---|
| Keep an ordered list you add to and index into | List<T> |
| Look up values by a key | Dictionary<TKey, TValue> |
| Track unique items / test membership fast | HashSet<T> |
| Process items in arrival order | Queue<T> |
| Process the newest item first | Stack<T> |
| Keep keys sorted | SortedDictionary / SortedSet |
Test yourself
Which collection automatically ignores duplicate values?
- List<T>
- Queue<T>
- HashSet<T>
- Stack<T>
After Push(1); Push(2); Push(3); on a Stack<int>, what does Pop() return?
- 1
- 2
- 3
- null
What happens when you read dict["missing"] for a key that does not exist?
- Returns null
- Returns the default value
- Throws KeyNotFoundException
- Adds the key