<aside> Collections in C# allow us to work with groups of objects. Each type has unique benefits for different scenarios.
π List
</aside>
A List is like a flexible array - it can grow or shrink as needed.
// Creating Lists
List<string> cities = new List<string>();
List<string> cities = new List<string> { "KΓΈbenhavn", "Aalborg", "Odense" };
// Adding items
cities.Add("Roskilde");
cities.Insert(2, "SorΓΈ");
π― Queue
Queues use First-In-First-Out (FIFO) - like a line at a store.
Queue<string> customers = new Queue<string>();
customers.Enqueue("Customer 1"); // Add to end
string next = customers.Dequeue(); // Remove from front
string peek = customers.Peek(); // Look at front
π Stack
Stacks use Last-In-First-Out (LIFO) - like a stack of plates.
Stack<string> cards = new Stack<string>();
cards.Push("Spar Es"); // Add to top
string top = cards.Pop(); // Remove from top
string peek = cards.Peek(); // Look at top
Dictionaries store key-value pairs for quick lookups.
Dictionary<string, int> grades = new Dictionary<string, int>();
grades.Add("Alice", 95);
grades["Bob"] = 87;
// Safe access
if (grades.TryGetValue("Alice", out int grade))
{
Console.WriteLine($"Grade: {grade}");
}
| Type | Best For |
|---|---|
| List | Dynamic collections |
| Queue | Processing in order |
| Stack | Reverse processing |
| Dictionary | Key-based lookups |
<aside> π‘ Best Practices: β’ Use plural names for collections β’ Choose appropriate type for your needs β’ Handle errors when accessing items β’ Check for null/empty collections
</aside>