Chapter 20: Collections and Generics in Depth

We already saw the basics of collections earlier, but now we’re going deep into the most important generic collections you’ll use every single day in real-world C# programming.

We’ll cover:

  • List<T> (dynamic array – most common)
  • Dictionary<TKey, TValue> (fast key-value lookups)
  • HashSet<T> (unique items, super-fast checks)
  • Queue<T> (FIFO – first in, first out)
  • Stack<T> (LIFO – last in, first out)
  • Sorted collections (SortedList, SortedDictionary, SortedSet)
  • Custom comparers (when you want to sort things your own way)

I’m going to explain everything very slowly, step by step, with tons of real-life examples, clear analogies, and practical mini-projects — just like we’re sitting together in Hyderabad looking at the same screen. Let’s dive in! 🚀

1. Quick Recap: Why Generic Collections?

  • Generic → type-safe (List<int> won’t let you add strings)
  • Dynamic → grow/shrink automatically (unlike arrays)
  • Powerful methods → .Add(), .Remove(), .Contains(), .FindAll(), .Sort()…
  • All live in System.Collections.Generic namespace

Important: Always use using System.Collections.Generic; at the top of your file!

2. List<T> – The King of Collections (Dynamic Array)

When to use: You want an ordered, growable list of items (like a shopping cart, list of students, recent messages…)

Key methods:

Method/Property What it does Example
.Add(item) Add to the end friends.Add(“Rahul”);
.Insert(index, item) Insert at specific position friends.Insert(0, “Priya”);
.Remove(item) Remove first occurrence friends.Remove(“Amit”);
.RemoveAt(index) Remove by index friends.RemoveAt(2);
.Contains(item) Check if exists if (friends.Contains(“Sneha”))
.IndexOf(item) Get position (-1 if not found) int pos = friends.IndexOf(“Vikram”);
.Count Number of items friends.Count
.Clear() Remove everything friends.Clear();
.Sort() Sort (needs IComparable or custom comparer) friends.Sort();

Real example – Student list manager

C#

3. Dictionary<TKey, TValue> – Super-Fast Lookup by Key

When to use: You want to look up values by a unique key very quickly (phone book, user ID → user data, product code → price…)

Key points:

  • Keys must be unique
  • Keys cannot be null (values can)
  • Very fast lookup: O(1) average time

Key methods:

Method/Property What it does Example
.Add(key, value) Add key-value pair users.Add(101, “Rahul”);
[key] = value Set or overwrite users[101] = “Priya”;
.TryGetValue(key, out value) Safe get (no exception) users.TryGetValue(999, out string name)
.ContainsKey(key) Check if key exists if (users.ContainsKey(101))
.Remove(key) Remove by key users.Remove(101);
.Keys / .Values Get all keys or values foreach (var k in users.Keys)
.Count Number of pairs users.Count

Real example – Phone book

C#

4. HashSet<T> – Unique Items & Super-Fast Contains

When to use: You want a collection of unique items and very fast checks if something exists (no duplicates allowed)

Key methods:

Method What it does Example
.Add(item) Add if not already present ids.Add(101);
.Contains(item) Check existence (very fast!) ids.Contains(101)
.Remove(item) Remove if exists ids.Remove(999);
.UnionWith(other) Combine two sets set1.UnionWith(set2);
.IntersectWith(other) Keep only common items set1.IntersectWith(set2);

Real example – Unique user IDs

C#

5. Queue<T> – First In, First Out (FIFO)

When to use: Tasks that must be processed in order (print jobs, customer queue, message queue…)

Key methods:

Method What it does Example
.Enqueue(item) Add to the end queue.Enqueue(“Task 1”);
.Dequeue() Remove and return from front string task = queue.Dequeue();
.Peek() Look at front without removing string next = queue.Peek();
.Count Number of items queue.Count

Example – Customer service queue

C#

6. Stack<T> – Last In, First Out (LIFO)

When to use: Undo/redo, browser back button, function call stack, parsing expressions…

Key methods:

Method What it does Example
.Push(item) Add to top stack.Push(“Page 1”);
.Pop() Remove and return from top string page = stack.Pop();
.Peek() Look at top without removing string top = stack.Peek();

Example – Browser history (back button)

C#

7. Sorted Collections – Always Keep Items Sorted

Collection Key Features When to use
SortedList<TKey, TValue> Sorted by key, like sorted Dictionary Need sorted key-value pairs
SortedDictionary<TKey, TValue> Like Dictionary but always sorted by key Fast insert + always sorted
SortedSet<T> Unique items, always sorted Unique + sorted collection

Example – SortedSet

C#

8. Custom Comparers – Sort Your Way!

By default, sorting uses IComparable (numbers, strings, DateTime…).

For custom objects or custom order → create a comparer.

Example – Sort Students by Marks descending

C#

Mini-Project: Library Management System

C#

Summary – What We Learned Today

  • List<T> → ordered, growable, most common
  • Dictionary<TKey, TValue> → fast lookup by key
  • HashSet<T> → unique items, fast .Contains()
  • Queue<T> → FIFO (first in first out)
  • Stack<T> → LIFO (last in first out)
  • Sorted collections → SortedList, SortedDictionary, SortedSet
  • Custom comparers → control sorting exactly how you want

Your Homework (Super Practical!)

  1. Create a new console project called CollectionsDeepDive
  2. Create a Movie Library system with:
    • List<Movie> (Title, Director, Year, Genre, Rating)
    • Dictionary<string, List<Movie>> → genre → list of movies
    • HashSet<string> → unique directors
    • SortedSet<Movie> → sorted by Rating descending (use custom comparer)
    • Queue<Movie> → watchlist (add & watch next)
    • Stack<Movie> → recently watched (undo watch)
  3. Add methods to add movie, search by genre, get top 3 rated movies, etc.

Next lesson: File I/O and Serialization – we’re going to learn how to save and load data to files and JSON!

You’re doing absolutely fantastic! 🎉 Any collection confusing? Want more examples with custom comparers or SortedSet? Just tell me — I’m right here for you! 💙

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *