1. Introduction
Let's be real, arrays are awesome, but they have their limits. Need to change the size? You'll have to make a new array and copy everything by hand! Need to quickly find an element by key? The array says: "Well, try to do it yourself".
Real life is full of situations where arrays are just awkward. Imagine you're writing an app to keep track of books in a library (hey, that's our little learning system!). At first, you have 5 books — an array seems fine. A week later, there are 500, and after another month, someone returned a book, someone lost one... That's when collections come to the rescue!
Collections are like containers that can:
- Automatically change their size.
- Give you fast search, add, and remove operations.
- Offer more convenient ways to handle data: sorting, filtering, batch processing.
.NET has several key "families" of collections. Today we'll meet the main ones: lists (List<T>), dictionaries (Dictionary<TKey, TValue>), sets (HashSet<T>), queues, stacks, and also the interfaces behind them.
2. Main Types of Collections
Even though we haven't dived into specific generic collection types yet, it's important to get what the main categories of collections are and what they're good for. Think of them as different kinds of "containers," each with its own quirks:
Lists
What's this? An ordered sequence of elements. Like a shopping list or a class roster.
Key features: Elements have order (you can get them by index, just like in an array). Can have duplicate elements. Size is dynamic.
When to use? When the order of elements matters, and you want to quickly add/remove elements at the end, or get elements by their position.
Real-life example: Checkout line, webinar participants list, animation frame sequence.
Dictionaries/Maps
What's this? A set of "key-value" pairs. Like a real dictionary, where each word (key) has its own meaning (value).
Key features: Each key is unique. The key is used for fast lookup of the value. Order of elements is usually not guaranteed.
When to use? When you need to quickly find a value by some unique identifier (key).
Real-life example: Address book (name - phone), product database (product ID - description), app settings (setting name - value).
Sets
What's this? An unordered set of unique elements. Like a math set.
Key features: Can't have duplicate elements. Order is not guaranteed. Optimized for checking if an element exists and for set operations (union, intersection).
When to use? When you need to store unique values and quickly check if something is in the set.
Real-life example: List of unique website visitors, set of tags for an article, autocomplete word list (no repeats).
Queues
What's this? A collection that works on the "first in — first out" principle (FIFO - First-In, First-Out).
Key features: Elements are added to the end of the queue and removed from the front.
When to use? Modeling processes where processing order matters, like a support ticket system, print queue.
Stacks
What's this? A collection that works on the "last in — first out" principle (LIFO - Last-In, First-Out).
Key features: Elements are added and removed from one end (the top of the stack).
When to use? Tracking action history (undo in an editor), handling nested structures, recursion.
Differences Between Collection Types
| Collection Type | Analogy | Main Principle | Index Access? | Element Order? | Duplicates Allowed? | Main Operations |
|---|---|---|---|---|---|---|
| Array | Row of numbered cells | Fixed size | Yes | Yes | Yes | Get/set by index |
| List | Shopping list | Dynamic, ordered | Yes | Yes | Yes | Add, remove, search |
| Dictionary | Dictionary (key-value) | Unique keys | No | No (usually) | No (by key) | Get by key, add |
| Set | Set of unique objects | Only unique elements | No | No | No | Check existence, union |
| Queue | Checkout line | FIFO (First in - first out) | No | Yes | Yes | Add to end, remove from front |
| Stack | Stack of plates | LIFO (Last in - first out) | No | Yes | Yes | Add to top, remove from top |
3. List: List<T>
The list is the most used collection in C#. Even more than arrays. A list is a collection that's like an array, but it can grow by itself. You can add and remove elements without a headache.
using System;
using System.Collections.Generic;
var numbers = new List<int>(); // Creating an empty list of integers
numbers.Add(10); // Adding an element
numbers.Add(15);
numbers.Add(42);
Console.WriteLine(numbers[0]); // 10
numbers.Remove(15); // Removing an element by value
foreach (var number in numbers)
{
Console.WriteLine(number);
}
// Will print: 10 and 42
Why is List<T> better than an array for a data collection when you don't know the size in advance?
— Because you don't have to manually allocate more memory and copy the array when adding elements — the collection does it all for you!
When to use List<T>?
- Dynamic list, when you want to add, remove, or change elements.
- You don't need fast lookup by key (that's what dictionaries are for).
- Often used for working with ordered sets.
4. Dictionary Dictionary<TKey, TValue>
An array (and a list) lets you store a list of values in array cells, and each cell has an index. But a dictionary is a collection that lets you use a string (name) instead of a number (index). This name is called a key.
If you need to quickly get a value by some key (like by library card number — reader's name), you need a dictionary.
using System.Collections.Generic;
var phoneBook = new Dictionary<string, string>();
phoneBook["Anya"] = "+79992221133";
phoneBook["Maksim"] = "+79998887766";
Console.WriteLine(phoneBook["Anya"]); // +79992221133
// You can check if a key exists:
if (phoneBook.ContainsKey("Vasya"))
{
Console.WriteLine(phoneBook["Vasya"]);
}
else
{
Console.WriteLine("No such number!");
}
Fun fact: Dictionaries are often called "associative arrays." They're built on hash tables, which makes key lookups super fast (almost instant, unless you hit collisions — but that's for later).
Key Features
- Key is unique: you can't have two identical keys in a dictionary.
- Values can repeat.
- Super fast search, add, and remove by key.
5. Set: HashSet<T>
Besides lists and dictionaries, sets are also super popular. It's almost like a list, just simpler: a list without a fixed order of elements. A set just stores a bunch of values, for situations where order doesn't matter.
For example, if you just need to know if something is in the set, no duplicates, and order doesn't matter — use a set.
using System.Collections.Generic;
var knownUsers = new HashSet<string>();
knownUsers.Add("admin");
knownUsers.Add("guest");
knownUsers.Add("admin"); // Adding again — ignored
Console.WriteLine(knownUsers.Contains("admin")); // True
Console.WriteLine(knownUsers.Count); // 2
A set checks if an element exists really fast.
Why use sets?
— Like, if you want to store all unique users who opened the app this month, or say, a list of unique book authors.
Features
- Stores only unique elements (adding a duplicate is ignored).
- No indexes like a list.
- Fast existence check.
6. Queues and Stacks
There are also structures for special cases: queue and stack. Basically, they're like lists, but with controlled adding and removing of elements.
Queue<T>: queue (first in — first out)
Sometimes you need to keep a "queue" — new elements go to the end, and you take them from the front.
using System.Collections.Generic;
var queue = new Queue<string>();
queue.Enqueue("First");
queue.Enqueue("Second");
queue.Enqueue("Third");
Console.WriteLine(queue.Dequeue()); // "First"
Console.WriteLine(queue.Peek()); // "Second", but doesn't remove
Stack<T>: stack (first in — last out)
A stack works the other way: last in — first out. Used in parsers, function call handling, and even undo actions in editors.
using System.Collections.Generic;
var stack = new Stack<string>();
stack.Push("One");
stack.Push("Two");
stack.Push("Three");
Console.WriteLine(stack.Pop()); // "Three"
Console.WriteLine(stack.Peek()); // "Two"
7. Table: Comparing Main Collections
| Collection | Unique Elements | Index Access | Fast Key Lookup | Insert/Remove Operations |
|---|---|---|---|---|
|
No | Yes | No | Fast at end |
|
Keys | No | Yes | Fast by key |
|
Yes | No | Yes* | Fast by value |
|
No | No | No | Fast (FIFO) |
|
No | No | No | Fast (LIFO) |
We'll dig into each collection in detail in the next lectures. And we'll start with the mysterious letter <T>...
GO TO FULL VERSION