🗃️ C# Collections: Your Magical Storage Boxes
Imagine you have different types of boxes to organize your toys. Each box has special powers!
🎭 The Story of Four Amazing Containers
Once upon a time, there were four magical containers in the land of C#. Each one had a special superpower for storing things. Let’s meet them!
📖 Dictionary: The Label Maker
What Is It?
A Dictionary is like a box where every toy has a name tag attached to it.
Think of it like: Your school cubby! Each cubby has a student’s name, and inside is that student’s stuff. You say “Give me Sarah’s backpack” and boom—you get it instantly!
// Creating your cubby system
Dictionary<string, string> cubbies =
new Dictionary<string, string>();
// Adding items to cubbies
cubbies["Sarah"] = "Blue backpack";
cubbies["Tom"] = "Red lunchbox";
cubbies["Mia"] = "Purple jacket";
// Getting Sarah's item
string item = cubbies["Sarah"];
// Result: "Blue backpack"
Why Is Dictionary Special?
| Feature | What It Means |
|---|---|
| Key | The name tag (must be unique!) |
| Value | The actual item stored |
| Super Fast | Finds items instantly |
Real-Life Examples
// Phone contacts
Dictionary<string, string> contacts =
new Dictionary<string, string>();
contacts["Mom"] = "555-1234";
contacts["Dad"] = "555-5678";
// Game scores
Dictionary<string, int> scores =
new Dictionary<string, int>();
scores["Player1"] = 100;
scores["Player2"] = 85;
Key Dictionary Methods
// Check if a key exists
if (cubbies.ContainsKey("Sarah"))
{
Console.WriteLine("Sarah has a cubby!");
}
// Safe way to get values
if (cubbies.TryGetValue("Tom", out string stuff))
{
Console.WriteLine(quot;Tom has: {stuff}");
}
// Remove an item
cubbies.Remove("Mia");
// Count items
int total = cubbies.Count;
🌟 Golden Rule: Every key must be unique! You can’t have two “Sarah” cubbies.
🎯 HashSet: The “No Copies Allowed” Club
What Is It?
A HashSet is like a special club where no duplicates are allowed. If you try to add something twice, it just ignores the second one!
Think of it like: A birthday party guest list. Each person can only be on the list once—writing “Emma” twice doesn’t invite two Emmas!
// Creating a guest list
HashSet<string> guestList = new HashSet<string>();
// Adding guests
guestList.Add("Emma");
guestList.Add("Liam");
guestList.Add("Emma"); // Ignored! Emma's already there
Console.WriteLine(guestList.Count);
// Result: 2 (not 3!)
Why Use HashSet?
graph TD A["Add Item"] --> B{Already exists?} B -->|Yes| C["Ignore it"] B -->|No| D["Add to set"] C --> E["Set unchanged"] D --> E
Cool HashSet Tricks
HashSet<int> myNumbers = new HashSet<int>
{ 1, 2, 3, 4, 5 };
HashSet<int> yourNumbers = new HashSet<int>
{ 4, 5, 6, 7, 8 };
// Numbers we BOTH have
myNumbers.IntersectWith(yourNumbers);
// Result: { 4, 5 }
// Combine all unique numbers
HashSet<int> all = new HashSet<int>
{ 1, 2, 3, 4, 5 };
all.UnionWith(new HashSet<int> { 4, 5, 6, 7, 8 });
// Result: { 1, 2, 3, 4, 5, 6, 7, 8 }
When to Use HashSet?
- ✅ Removing duplicates from a list
- ✅ Checking if something exists (super fast!)
- ✅ Finding common items between groups
- ✅ Tracking “already seen” items
📚 Queue: The Fair Line
What Is It?
A Queue is like a line at the ice cream shop. First person in line gets served first!
Think of it like: Waiting for a slide at the playground. The kid who got in line first goes down the slide first. No cutting!
// Kids waiting for the slide
Queue<string> slideLine = new Queue<string>();
// Kids join the line
slideLine.Enqueue("Alex"); // First in line
slideLine.Enqueue("Beth"); // Second
slideLine.Enqueue("Carlos"); // Third
// Who goes down the slide?
string firstKid = slideLine.Dequeue();
// Result: "Alex" goes first!
// Who's next?
string nextKid = slideLine.Peek();
// Result: "Beth" (but she stays in line)
Queue Flow
graph LR A["New Person"] -->|Enqueue| B["Back of Line"] B --> C["Middle"] C --> D["Front of Line"] D -->|Dequeue| E["Gets Served!"]
Queue Keywords
| Word | Meaning |
|---|---|
| Enqueue | Join the back of the line |
| Dequeue | Leave from the front |
| Peek | Look at who’s first (without removing) |
| FIFO | First In, First Out |
Real Examples
// Print jobs waiting
Queue<string> printJobs = new Queue<string>();
printJobs.Enqueue("Report.pdf");
printJobs.Enqueue("Photo.jpg");
printJobs.Enqueue("Letter.doc");
// Process jobs in order
while (printJobs.Count > 0)
{
string job = printJobs.Dequeue();
Console.WriteLine(quot;Printing: {job}");
}
🥞 Stack: The Pancake Pile
What Is It?
A Stack is like a pile of pancakes. You can only take the top pancake!
Think of it like: A stack of books on your desk. To get the bottom book, you have to remove all the books on top first!
// Stacking pancakes
Stack<string> pancakes = new Stack<string>();
// Adding pancakes (bottom to top)
pancakes.Push("Blueberry"); // Bottom
pancakes.Push("Chocolate"); // Middle
pancakes.Push("Maple"); // Top!
// Eating pancakes (top first!)
string firstBite = pancakes.Pop();
// Result: "Maple" (the top one!)
// What's on top now?
string next = pancakes.Peek();
// Result: "Chocolate"
Stack Flow
graph TD subgraph Stack A["TOP: Maple"] B["Chocolate"] C["BOTTOM: Blueberry"] end D["Pop"] --> A E["Push New"] --> A
Stack Keywords
| Word | Meaning |
|---|---|
| Push | Put on top of the pile |
| Pop | Take from the top |
| Peek | Look at the top (without removing) |
| LIFO | Last In, First Out |
Real Examples
// Undo button in a drawing app
Stack<string> history = new Stack<string>();
// User draws things
history.Push("Drew circle");
history.Push("Drew square");
history.Push("Drew triangle");
// User clicks Undo
string undone = history.Pop();
// Undoes: "Drew triangle" (most recent!)
🎪 Quick Comparison
| Container | Superpower | Best For |
|---|---|---|
| Dictionary | Find by name tag | Phone contacts, settings |
| HashSet | No duplicates | Guest lists, unique items |
| Queue | Fair line (FIFO) | Waiting lists, print jobs |
| Stack | Pancake pile (LIFO) | Undo button, browser back |
🧙♂️ Magic Memory Trick
Dictionary = Directory (look up by name) HashSet = Has it? (yes/no, no copies) Queue = Queing up fairly (first come, first served) Stack = Stacked plates (take from top)
🎯 When to Use What?
graph TD A["Need to store data?"] --> B{Need to find by key?} B -->|Yes| C["Use Dictionary"] B -->|No| D{Need to prevent duplicates?} D -->|Yes| E["Use HashSet"] D -->|No| F{Need fair order?} F -->|Yes, FIFO| G["Use Queue"] F -->|No, LIFO| H["Use Stack"]
🌈 Fun Summary
| You Want To… | Use This |
|---|---|
| Store name-value pairs | Dictionary<K,V> |
| Keep only unique items | HashSet<T> |
| Process in arrival order | Queue<T> |
| Go back/undo (most recent first) | Stack<T> |
Remember: Each container has its superpower. Pick the right one for your mission!
Now you’re ready to organize data like a pro! Go build something amazing! 🚀
