Collections and Data Structures
7 min read
Hello, Camper! ποΈ Welcome to one of the most critical sections of your C# journey.
Until now, you've likely been storing data in single variables like int age = 25; or string name = "Lara";. But real-world applications deal with volume. Imagine trying to store the names of 1,000 users. Would you create string name1, string name2... all the way to name1000?
Absolute chaos. π€―
That is the problem Collections solve. They are containers that hold groups of objects.
In C#, the System.Collections.Generic namespace provides us with the tools to store, manage, and manipulate data efficiently. Understanding how these work "under the hood" distinguishes a coder from a software engineer.
Let's dive in. π
1. Arrays: Fixed-Size Data Collections
π§ Definition & The Problem
Definition: An Array is a data structure that stores a fixed-size sequential collection of elements of the same type.
The Problem: You need to store 5 test scores. You want them grouped together so you can calculate an average without writing 5 separate variable names.
The Solution: An Array allocates a contiguous block of memory to hold these specific items side-by-side.
π» Syntax and Usage
To declare an array, we specify the type followed by brackets [].
// Declaration and Initialization
int[] testScores = new int[5]; // Creates a container for exactly 5 integers
// Setting values (Remember: C# is 0-indexed!)
testScores[0] = 95;
testScores[1] = 88;
// ... and so on
// Inline initialization (Industry standard for known values)
string[] days = { "Mon", "Tue", "Wed", "Thu", "Fri" };βοΈ Under the Hood
When you say new int[5], C# talks to the computer's memory (RAM) and asks: "Give me space for 5 integers right next to each other."
Because they are right next to each other, the computer can find testScores[3] instantly using simple math (Start Address + 3 steps). This makes reading arrays extremely fast.
β οΈ Industry Reality Check
Arrays are the "metal" of C# collections. They are fast but rigid.
- Limitation: Once created, you cannot change the size. If you need a 6th test score, you have to create a brand new, larger array and copy everything over.
- Usage: Use arrays when you are 100% sure the number of items won't change (e.g., coordinates in a 3D point
x,y,z, or days of the week).
Fun Fact: The error
IndexOutOfRangeExceptionis the C# developer's rite of passage. It means you tried to access item #11 in a 10-item array. The computer looked at that memory address and said, "There's nothing here but void and ghosts." π»
2. Lists: Dynamic and Flexible Arrays
π§ Definition & The Problem
Definition: A List<T> is a generic collection that provides the functionality of an array but can dynamically resize itself.
The Problem: In the real world, we rarely know how much data we have. A shopping cart starts empty. Users add items. Users remove items. An Array's fixed size makes this painful.
The Solution: The List<T>. The <T> stands for "Type" (Generics). It means you can have a List of ints, strings, or custom Objects.
π» Syntax and Usage
You must include using System.Collections.Generic; at the top of your file.
using System.Collections.Generic;
// Creating a list of strings
List<string> shoppingCart = new List<string>();
// 1. Adding items
shoppingCart.Add("Milk");
shoppingCart.Add("Eggs");
shoppingCart.Add("Coffee"); // Count is now 3
// 2. Accessing items (Just like arrays)
Console.WriteLine(shoppingCart[0]); // Output: Milk
// 3. Removing items
shoppingCart.Remove("Eggs"); // "Coffee" shifts down to index 1βοΈ Under the Hood (Important Interview Knowledge)
A List isn't magic; it is actually just a wrapper around an Array!
- When you create a
new List(), C# creates a small internal array (usually size 4). - When you
.Add()the 5th item, C# realizes the internal array is full. - Resizing: It creates a new array that is double the size (size 8), copies your 4 items to the new one, and dumps the old one.
Performance Tip: If you know you are about to add 10,000 items, use new List<int>(10000). This sets the initial capacity, preventing the computer from having to resize and copy the array over and over again as it grows.
3. Dictionaries: Key-Value Pairs for Quick Lookups
π§ Definition & The Problem
Definition: A Dictionary<TKey, TValue> is a collection that stores data in key-value pairs. Each key must be unique.
The Problem: Imagine you have a List<User> with 10,000 users. You want to find the user with ID "A782". With a List, you have to loop through the list, checking every single user until you find them. This is slow ().
The Solution: Dictionaries allow you to look up data using a specific identifier (Key) instantly (), rather than an index number.
π» Syntax and Usage
Think of a real-world dictionary. You don't read every word to find "Programming"; you jump straight to "P".
// Key is string (Country Code), Value is string (Country Name)
Dictionary<string, string> countryCodes = new Dictionary<string, string>();
// Adding data
countryCodes.Add("NP", "Nepal");
countryCodes.Add("US", "United States");
countryCodes.Add("JP", "Japan");
// Fast Lookup
string myCountry = countryCodes["NP"];
Console.WriteLine(myCountry); // Output: Nepal
// Safer way to lookup (Prevents crashing if key doesn't exist)
if (countryCodes.TryGetValue("FR", out string result))
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("Key not found!");
}βοΈ Under the Hood
Dictionaries use a concept called Hashing. When you save "Nepal" under the key "NP", the computer runs a math formula on "NP" to generate a specific memory address. When you ask for "NP" later, it runs the math again and goes straight to that address. It doesn't search; it teleports. β‘
β οΈ Industry Standard
- Unique Keys: You cannot have two keys named "NP". The program will crash.
- Use Case: Caching, Config settings, finding objects by ID.
4. HashSets and Queues: Specialized Collections
Sometimes Lists and Dictionaries aren't the right tool for the job.
A. HashSet <T>
Definition: A collection containing distinct (unique) elements. It has no specific order.
The Problem: You have a list of email addresses entered by users for a newsletter, but users accidentally clicked "Submit" twice. You have duplicates.
The Solution: HashSet automatically rejects duplicates.
HashSet<string> emails = new HashSet<string>();
emails.Add("[email protected]");
emails.Add("[email protected]");
emails.Add("[email protected]"); // returns false, does NOT add.
Console.WriteLine(emails.Count); // Output: 2Use this when mathematical uniqueness is required.
B. Queue <T> (FIFO)
Definition: A First-In-First-Out collection.
The Problem: You are building a printer driver. If User A hits print, and then User B hits print, User A's document should finish first.
The Solution: A Queue.
Queue<string> printerQueue = new Queue<string>();
// Enqueue (Add to back)
printerQueue.Enqueue("Document1.pdf");
printerQueue.Enqueue("Document2.pdf");
// Dequeue (Remove from front)
string currentDoc = printerQueue.Dequeue(); // Returns "Document1.pdf"
// Queue now only contains Document2Comparison: There is also a
Stack<T>(LIFO - Last In First Out). Think of a stack of plates or the "Undo" (Ctrl+Z) button. The last thing you did is the first thing removed.
π οΈ Summary & Best Practices
| Collection | Ordering? | Allows Duplicates? | Best Used For... |
|---|---|---|---|
| Array | Yes (Indexed) | Yes | Fixed size, maximum performance. |
| List | Yes (Indexed) | Yes | General purpose, dynamic size. |
| Dictionary | No | No (Keys) | Looking up items by ID/Name. |
| HashSet | No | No | Ensuring items are unique. |
| Queue | Yes (FIFO) | Yes | Processing tasks in order. |
π§ Senior Dev Tips:
- Avoid
ArrayList: You might see this in old tutorials. It is non-generic (stores everything asobject) and causes performance issues due to "boxing/unboxing". Always useList<T>. - Looping: You can loop through all these collections using the
foreachloop.csharpforeach(var item in myCollection) { /* do work */ } - LINQ: In the next chapters, you will learn about LINQ. It works beautifully with all these collections to filter and sort data (e.g.,
list.Where(x => x > 10)).
π References & Further Reading
- MS Docs: Arrays
- MS Docs: List Class
- MS Docs: Dictionary Class
- MS Docs: Selection of Collection Class
Happy Coding! πΉ
Challenge
Challenge: E-commerce Order Processing System
You are tasked with building the core logic for an e-commerce order processing system. Your implementation must use the most appropriate generic collection for each component to ensure high performance and correctness based on the system's requirements.
Requirements:
Implement the
OrderProcessorclass.Use the most suitable collection from
System.Collections.Genericfor each private field:- A collection to manage incoming orders. It is critical that orders are processed in the exact sequence they are received (First-In-First-Out).
- A collection to store customer data. The system must be able to retrieve any customer's profile almost instantly using their unique integer
CustomerIdas the lookup key. - A collection to log the Stock Keeping Units (SKUs) of all unique products that have been processed. This collection must automatically prevent duplicate SKU entries.
Implement the following public methods inside the
OrderProcessorclass:void AddNewOrder(Order newOrder): Adds a given order to the processing queue.void RegisterCustomer(Customer newCustomer): Stores a new customer's data for fast lookup.Order ProcessNextOrder(): This method should:
a. Remove the next order from the processing queue.
b. For each product within that order, add itsSKUto your collection of unique product SKUs.
c. Return the processed order.
d. If the queue is empty, it must returnnull.Customer GetCustomerById(int customerId): Retrieves a customer's data using their ID. If the customer is not found, returnnull.HashSet<string> GetUniqueProductSKUs(): Returns the collection containing all unique product SKUs that have been processed so far.
Expected result
Your completed code should feature a fully implemented OrderProcessor class.
The class must contain three private fields, correctly initialized as:
- A
Queue<Order>for managing incoming orders. - A
Dictionary<int, Customer>for storing and looking up customer data. - A
HashSet<string>for tracking unique product SKUs.
- A
The
AddNewOrdermethod must use theEnqueuemethod of the queue.The
RegisterCustomermethod must add the customer to the dictionary, usingCustomerIdas the key.The
ProcessNextOrdermethod must correctly use theDequeuemethod, handle the case of an empty queue by returningnull, and iterate through the order's products to add eachSKUto theHashSet.The
GetCustomerByIdmethod should efficiently retrieve a customer from the dictionary, for example by usingTryGetValue, and returnnullif the key does not exist.The
GetUniqueProductSKUsmethod should return theHashSetinstance containing the processed SKUs.