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
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
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.
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
| Collection | Best at | Watch out for |
|---|---|---|
List<T> | Fast access by index, adding at the end | Contains and inserting at the front scan or shift every item |
Dictionary<K,V> | Very fast lookup by key on average | Keys must be unique; order is not guaranteed |
HashSet<T> | Fast "is this already here?" checks | No index and no duplicates |
SortedDictionary<K,V> | Keys kept in sorted order | Slower than a normal dictionary |
Queue<T> / Stack<T> | Adding and removing at one end | No access to items in the middle |
LinkedList<T> | Inserting or removing next to a known node | No 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
foreachthrows anInvalidOperationException. UseRemoveAll, loop backwards withfor, or build a new list. - Using old non-generic types like
ArrayListandHashtable, 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.