HashSet<T>, SortedSet<T>, Queue<T>, Stack<T>
Understand unique sets vs ordered sets and FIFO/LIFO collections; practice Add/Contains, Enqueue/Dequeue, Push/Pop.
Shapes of collections
Goal: Pick the right collection.
- HashSet<T>: unique, fast lookup
- SortedSet<T>: unique + sorted
- Queue<T>: FIFO
- Stack<T>: LIFO
HashSet basics
HashSet<T> keeps unique values; Add returns false on duplicates; Contains is fast.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
HashSet<string> tags = new HashSet<string>();
bool a1 = tags.Add("red"); // true
bool a2 = tags.Add("blue"); // true
bool a3 = tags.Add("red"); // false (duplicate ignored)
Console.WriteLine("Has red? " + tags.Contains("red"));
Console.WriteLine("Count = " + tags.Count); // 2
}
}
All lessons in this course
- HashSet , SortedSet , Queue , Stack
- ConcurrentDictionary , immutable collections
- Equality & hashing (value vs reference)