C# Collections: Understanding and Using Data Structures

Explore the most important C# collection types, including List, Dictionary, Queue, and Stack, and learn when to use each data structure.

Why Collections Matter

Collections in C# provide flexible, dynamically sized ways to store and manage groups of related data, offering far more functionality than fixed-size arrays.

List

List is one of the most commonly used collections, offering a dynamically resizable array-like structure that supports adding, removing, and searching elements with built-in methods.

Dictionary

Dictionaries store data as key-value pairs, allowing extremely fast lookups by key. They're ideal for scenarios where you need to associate unique identifiers with specific data, such as looking up a user by ID.

Queue and Stack

Queue follows a First-In-First-Out (FIFO) principle, useful for task scheduling, while Stack follows Last-In-First-Out (LIFO), commonly used for undo functionality or parsing expressions.

Choosing the Right Collection

Selecting the right collection type depends on your access patterns: use List for ordered, indexable data, Dictionary for fast key-based lookups, and Queue or Stack when order of processing matters.

Conclusion: C# collections give developers powerful, ready-to-use data structures for nearly any scenario. Knowing which one to reach for is a key skill that directly impacts the performance and clarity of your code.

The Core Collections in Code

using System;
using System.Collections.Generic;

var cities = new List<string> { "Delhi", "Pune" };
cities.Add("Noida");
cities.Insert(0, "Agra");
Console.WriteLine(cities[1]);              // Delhi
cities.RemoveAll(c => c.StartsWith("P"));  // removes Pune

var stock = new Dictionary<string, int> { ["pen"] = 40, ["notebook"] = 12 };
stock["pen"] -= 1;                         // update an existing key
if (stock.TryGetValue("eraser", out int qty))
    Console.WriteLine(qty);
else
    Console.WriteLine("Not stocked");

var tags = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "CSharp", "dotnet" };
tags.Add("csharp");                        // ignored, already present
Console.WriteLine(tags.Count);             // 2

var jobs = new Queue<int>();
jobs.Enqueue(101);
jobs.Enqueue(102);
Console.WriteLine(jobs.Dequeue());         // 101

var undo = new Stack<string>();
undo.Push("typed A");
undo.Push("typed B");
Console.WriteLine(undo.Pop());             // typed B

Notice TryGetValue. Reading stock["eraser"] directly would throw a KeyNotFoundException, so the "try" pattern is the safe default when a key may be missing.

The HashSet example also shows a useful trick: passing a comparer such as StringComparer.OrdinalIgnoreCase changes how items are matched. Dictionaries accept the same argument, which is handy for usernames, email addresses or product codes where letter case should not create separate entries. Without it, "CSharp" and "csharp" would be stored as two different values.

Comparing Speed and Behaviour

CollectionBest atWatch out for
List<T>Fast access by index, adding at the endContains and inserting at the front scan or shift every item
Dictionary<K,V>Very fast lookup by key on averageKeys must be unique; order is not guaranteed
HashSet<T>Fast "is this already here?" checksNo index and no duplicates
SortedDictionary<K,V>Keys kept in sorted orderSlower than a normal dictionary
Queue<T> / Stack<T>Adding and removing at one endNo access to items in the middle
LinkedList<T>Inserting or removing next to a known nodeNo index; often slower than a list in practice

A common upgrade is replacing list.Contains(x) inside a loop with a HashSet. On large data, this can turn a slow nested search into a quick lookup.

Interfaces, Threads and Read-only Views

Methods should usually accept the most general interface they need, such as IEnumerable<T> for reading in a loop or IReadOnlyList<T> when index access is required. Callers can then pass a list, an array or another collection without conversion.

Standard collections are not safe when several threads write at the same time. For shared data, use types from System.Collections.Concurrent, such as ConcurrentDictionary or ConcurrentQueue. If data should never change after creation, immutable collections from System.Collections.Immutable make that intention explicit.

Frequent Mistakes

  • Changing a collection inside foreach throws an InvalidOperationException. Use RemoveAll, loop backwards with for, or build a new list.
  • Using old non-generic types like ArrayList and Hashtable, which lose type safety and need casting.
  • Returning internal lists directly, letting callers modify private state; return a read-only view instead.
  • Ignoring capacity when you know the size in advance; new List<int>(10000) avoids repeated resizing.

Ready to Master C# Programming Course?

Join Uncodemy's hands-on training program with expert mentors and real-world projects.