Learn C# Β· 7/15

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 [].

csharp
// 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 IndexOutOfRangeException is 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.

csharp
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!

  1. When you create a new List(), C# creates a small internal array (usually size 4).
  2. When you .Add() the 5th item, C# realizes the internal array is full.
  3. 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 (O(n)O(n)).

The Solution: Dictionaries allow you to look up data using a specific identifier (Key) instantly (O(1)O(1)), 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".

csharp
// 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.

csharp
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: 2

Use 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.

csharp
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 Document2

Comparison: 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:

  1. Avoid ArrayList: You might see this in old tutorials. It is non-generic (stores everything as object) and causes performance issues due to "boxing/unboxing". Always use List<T>.
  2. Looping: You can loop through all these collections using the foreach loop.
    csharp
    foreach(var item in myCollection) { /* do work */ }
  3. 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

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:

  1. Implement the OrderProcessor class.

  2. Use the most suitable collection from System.Collections.Generic for 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 CustomerId as 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.
  3. Implement the following public methods inside the OrderProcessor class:

    • 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 its SKU to your collection of unique product SKUs.
      c. Return the processed order.
      d. If the queue is empty, it must return null.
    • Customer GetCustomerById(int customerId): Retrieves a customer's data using their ID. If the customer is not found, return null.
    • 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.

  1. 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.
  2. The AddNewOrder method must use the Enqueue method of the queue.

  3. The RegisterCustomer method must add the customer to the dictionary, using CustomerId as the key.

  4. The ProcessNextOrder method must correctly use the Dequeue method, handle the case of an empty queue by returning null, and iterate through the order's products to add each SKU to the HashSet.

  5. The GetCustomerById method should efficiently retrieve a customer from the dictionary, for example by using TryGetValue, and return null if the key does not exist.

  6. The GetUniqueProductSKUs method should return the HashSet instance containing the processed SKUs.

csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.