Roadmap › C# Language — Basics to Advanced › Module: Arrays and Collections
Lessons in this course (38)

12. SortedList, HashSet, Stack and Queue

BasicMediumLesson 12 of 38
csharp
// SortedList<TKey,TValue>: kept sorted by key; arrays inside → small memory, O(n) inserts
var ranks = new SortedList<int, string> { [3] = "Bronze", [1] = "Gold", [2] = "Silver" };
foreach (var kv in ranks) Console.WriteLine($"{kv.Key}: {kv.Value}");   // 1 Gold, 2 Silver, 3 Bronze
Console.WriteLine(ranks.Keys[0]);     // index access to keys/values

// HashSet<T>: unique items, O(1) Contains, set operations
var skills = new HashSet<string> { "C#", "SQL" };
skills.Add("C#");                     // ignored — returns false
skills.UnionWith(["Azure", "SQL"]);   // C#, SQL, Azure
skills.IntersectWith(["SQL", "Azure", "React"]);   // SQL, Azure

// Stack<T>: LIFO — last in, first out (undo, call stack, bracket matching)
var undo = new Stack<string>();
undo.Push("type A"); undo.Push("type B");
Console.WriteLine(undo.Peek());       // type B (look, don't remove)
Console.WriteLine(undo.Pop());        // type B (remove)
// undo.Pop() on an empty stack throws InvalidOperationException — use TryPop

// Queue<T>: FIFO — first in, first out (jobs, BFS, print queue)
var jobs = new Queue<string>();
jobs.Enqueue("email"); jobs.Enqueue("invoice");
Console.WriteLine(jobs.Dequeue());    // email
Console.WriteLine(jobs.TryPeek(out var next) ? next : "empty");   // invoice

// PriorityQueue<TElement,TPriority> (.NET 6): lowest priority value comes out first
var pq = new PriorityQueue<string, int>();
pq.Enqueue("low", 5); pq.Enqueue("urgent", 1);
Console.WriteLine(pq.Dequeue());      // urgent
CollectionOrdered byDuplicatesTypical use
SortedList<K,V>Key (array-based)Keys uniqueSmall, mostly-read sorted maps
SortedDictionary<K,V>Key (tree-based)Keys uniqueMany inserts/removes, sorted
HashSet<T> / SortedSet<T>None / sortedNoUniqueness, set maths
Stack<T>LIFOYesUndo, parsing
Queue<T>FIFOYesWork queues, BFS