Collection Basics

Back

Loading concept...

🎒 C# Collections: Your Magical Backpack of Data

Imagine you have a magical backpack. This isn’t just any backpack—it can hold toys, grow bigger when you need more space, and even help you find exactly what you’re looking for in seconds. That’s what Collections are in C#! They’re special containers that hold your data and make working with lots of stuff super easy.


🧸 List — Your Expandable Toy Box

A List<T> is like a toy box that:

  • Can hold as many toys as you want
  • Keeps everything in order
  • Lets you add, remove, or find toys easily

Creating Your Toy Box

// Make an empty toy box for strings
List<string> toys = new List<string>();

// Make a toy box with toys already inside!
List<string> myToys = new List<string>
{
    "Teddy Bear",
    "Robot",
    "Ball"
};

Common Operations — Playing with Your Toys

graph TD A["🎁 Your List"] --> B["Add"] A --> C["Remove"] A --> D["Find"] A --> E["Count"] B --> B1["toys.Add&#35;40;&&#35;39;Car&&#35;39;&#35;41;"] C --> C1["toys.Remove&#35;40;&&#35;39;Ball&&#35;39;&#35;41;"] D --> D1["toys.Contains&#35;40;&&#35;39;Robot&&#35;39;&#35;41;"] E --> E1["toys.Count"]

Adding toys:

myToys.Add("Dinosaur");        // Add at the end
myToys.Insert(0, "Doll");      // Add at position 0

Removing toys:

myToys.Remove("Ball");         // Remove by name
myToys.RemoveAt(1);            // Remove at position 1
myToys.Clear();                // Remove ALL toys!

Finding toys:

bool hasTeddy = myToys.Contains("Teddy Bear");
int position = myToys.IndexOf("Robot");
string first = myToys[0];       // Get first toy

Counting:

int howMany = myToys.Count;     // How many toys?

📜 Collection Interfaces — The Rules of the Game

Think of interfaces like rules that collections promise to follow. When someone says “I follow the IList rules,” you know exactly what they can do!

The Main Rules (Interfaces)

Interface What It Promises Real World
IEnumerable<T> “You can look at my items one by one” Walking through a line
ICollection<T> “You can count me and add/remove” A counted jar of candies
IList<T> “You can access me by position” Numbered lockers
IDictionary<K,V> “Find things by their name” A phone book
// Using interfaces makes code flexible!
IList<string> myList = new List<string>();
ICollection<int> myCollection = new List<int>();

Why use interfaces? Because you can change what’s inside later without breaking your code!


🚶 IEnumerable vs IEnumerator — The Walker and the Map

Imagine you’re at a zoo. You want to see all the animals.

  • IEnumerable = The zoo itself. It says: “I have animals you can visit!”
  • IEnumerator = Your guided tour. It keeps track of where you are and moves you forward.
graph TD A["🦁 IEnumerable"] -->|"GetEnumerator#40;#41;"| B["🗺️ IEnumerator"] B --> C["Current: Where am I?"] B --> D["MoveNext&#35;40;&#35;41;: Go forward!"] B --> E["Reset&#35;40;&#35;41;: Start over!"]

How They Work Together

List<string> animals = new List<string>
{
    "Lion", "Tiger", "Bear"
};

// IEnumerable way (easy!)
foreach (string animal in animals)
{
    Console.WriteLine(animal);
}

// IEnumerator way (manual control)
IEnumerator<string> tour = animals.GetEnumerator();
while (tour.MoveNext())
{
    Console.WriteLine(tour.Current);
}

Key Difference:

  • IEnumerable = “I CAN be walked through”
  • IEnumerator = “I AM walking through right now”

🔍 IQueryable vs IEnumerable — Local vs Remote Search

Imagine searching for a book:

  • IEnumerable = You grab ALL books, bring them home, THEN search through them on your desk.
  • IQueryable = You tell the librarian exactly what you want. They search and bring only matching books.
graph TD A["📚 Your Search"] --> B{Where's the data?} B -->|In Memory| C["IEnumerable"] B -->|In Database| D["IQueryable"] C --> E["Brings ALL data first&lt;br&gt;Then filters locally"] D --> F["Sends query to database&lt;br&gt;Returns only matches"]

The Big Difference

// IEnumerable - filters AFTER loading
IEnumerable<Student> students = GetStudents();
var tall = students.Where(s => s.Height > 5);
// All students loaded, then filtered

// IQueryable - filters AT the database
IQueryable<Student> dbStudents = db.Students;
var tall = dbStudents.Where(s => s.Height > 5);
// SQL sent: SELECT * WHERE Height > 5
Feature IEnumerable IQueryable
Where? In memory Database/remote
When filtered? After loading all Before loading
Speed for big data Slower 🐢 Faster 🚀
Best for Small lists, arrays Databases, APIs

🎨 Collection Initialization — Quick Setup Magic

Instead of adding items one by one, you can create collections with items already inside! It’s like buying a toy box that already has toys in it.

Old Way (Boring)

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

New Way (Fun!)

// Collection initializer
List<int> numbers = new List<int> { 1, 2, 3 };

// Dictionary initializer
Dictionary<string, int> ages = new Dictionary<string, int>
{
    { "Alice", 10 },
    { "Bob", 12 }
};

// Even cooler dictionary syntax!
Dictionary<string, int> ages2 = new Dictionary<string, int>
{
    ["Alice"] = 10,
    ["Bob"] = 12
};

Works with Any Collection!

// HashSet
HashSet<string> colors = new HashSet<string>
{
    "Red", "Blue", "Green"
};

// Stack
Stack<int> stack = new Stack<int>(
    new[] { 1, 2, 3 }
);

✨ Collection Expressions (C# 12+) — The Ultimate Shortcut

C# 12 introduced collection expressions—the shortest, cleanest way to create collections!

The Magic Syntax: [ ]

// Old ways
List<int> old1 = new List<int> { 1, 2, 3 };
int[] old2 = new int[] { 1, 2, 3 };

// NEW collection expression! 🎉
List<int> nums = [1, 2, 3];
int[] arr = [1, 2, 3];
Span<int> span = [1, 2, 3];

Spread Operator: Combine Collections

The .. operator lets you pour one collection into another!

int[] first = [1, 2, 3];
int[] second = [4, 5, 6];

// Combine them!
int[] all = [..first, ..second];
// Result: [1, 2, 3, 4, 5, 6]

// Mix and match!
int[] mixed = [0, ..first, 99, ..second, 100];
// Result: [0, 1, 2, 3, 99, 4, 5, 6, 100]

Empty Collections Made Easy

// Empty collection expression
List<string> empty = [];
int[] noNumbers = [];
graph TD A["Collection Expressions"] --> B["[1, 2, 3]"] A --> C["[] empty"] A --> D["[..a, ..b] spread"] B --> E["Arrays, Lists, Spans"] C --> F["Any collection type"] D --> G["Combine collections"]

🎯 Quick Summary

Concept What It Does Example
List Resizable ordered collection new List<int> { 1, 2 }
IEnumerable Can be looped through foreach works
IEnumerator Tracks position in loop MoveNext(), Current
IQueryable Query remote data smartly Database LINQ
Collection Init Create with items inside new List<int> { 1, 2 }
Collection Expr Shortest syntax (C# 12) [1, 2, 3]

🌟 You Did It!

You now understand how C# collections work! They’re just like magical containers that help you organize, find, and work with your data. Whether you need a simple list, want to loop through items, or query a database efficiently—you’ve got the tools!

Remember:

  • 📦 List = Your flexible, growable container
  • 📜 Interfaces = Rules collections follow
  • 🚶 IEnumerable/IEnumerator = The “what” vs “how” of looping
  • 🔍 IQueryable/IEnumerable = Remote vs local searching
  • 🎨 Initializers = Quick setup with items
  • Collection Expressions = The cleanest, shortest way!

Happy coding! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.