12 essential data structures for C# developers. Each one explained with Big O complexity, animated visuals, and real code samples you can copy.
T[]Fixed-size, contiguous block of memory. Elements are stored sequentially and accessed by index in constant time. The foundation of most other data structures.
arr[0] = 7
Complexity
When to use
// Declaration and initialization
int[] numbers = new int[5];
int[] primes = { 2, 3, 5, 7, 11 };
// Access and modify
primes[0] = 13; // O(1)
int third = primes[2]; // O(1) -> 5
// Iterate
foreach (int p in primes)
Console.Write(p + " ");
// Search
int idx = Array.IndexOf(primes, 7); // O(n) -> 3
Array.Sort(primes); // O(n log n)
int pos = Array.BinarySearch(primes, 7); // O(log n)List<T>Resizable array that automatically grows when capacity is exceeded. The most commonly used data structure in most languages. Doubles its internal storage when full, giving amortized O(1) appends.
arr[0] = 7
Complexity
When to use
var names = new List<string> { "Alice", "Bob" };
names.Add("Charlie"); // O(1) amortized
names.Insert(1, "Diana"); // O(n) - shifts elements
names.Remove("Bob"); // O(n) - shifts elements
names.RemoveAt(0); // O(n) - shifts elements
bool has = names.Contains("Charlie"); // O(n)
int idx = names.IndexOf("Diana"); // O(n)
// Sort and binary search
names.Sort(); // O(n log n)
names.ForEach(n => Console.Write(n + " "));Stack<T>Last-In-First-Out (LIFO) collection. Only the top element is accessible. Used for tracking state that must be unwound in reverse order.
Push 10
Complexity
When to use
var stack = new Stack<int>();
stack.Push(10); // O(1)
stack.Push(20);
stack.Push(30);
int top = stack.Peek(); // O(1) -> 30 (no removal)
int val = stack.Pop(); // O(1) -> 30 (removed)
Console.WriteLine(stack.Count); // 2
Console.WriteLine(stack.Contains(10)); // O(n) -> True
// Classic interview pattern: valid parentheses
bool IsValid(string s) {
var st = new Stack<char>();
foreach (char c in s) {
if (c == '(') st.Push(')');
else if (st.Count == 0 || st.Pop() != c) return false;
}
return st.Count == 0;
}Queue<T>First-In-First-Out (FIFO) collection. Elements are added at the back and removed from the front. Fundamental for breadth-first processing.
Enqueue 10
Complexity
When to use
var queue = new Queue<string>();
queue.Enqueue("Task A"); // O(1)
queue.Enqueue("Task B");
queue.Enqueue("Task C");
string first = queue.Peek(); // O(1) -> "Task A"
string next = queue.Dequeue(); // O(1) -> "Task A"
// Classic interview pattern: BFS level-order traversal
void BFS(TreeNode root) {
var q = new Queue<TreeNode>();
q.Enqueue(root);
while (q.Count > 0) {
var node = q.Dequeue();
Console.Write(node.Val + " ");
if (node.Left != null) q.Enqueue(node.Left);
if (node.Right != null) q.Enqueue(node.Right);
}
}Dictionary<K,V>Maps keys to values using a hash function for near-constant-time lookups. The single most important data structure for coding interviews. Every language has a built-in implementation.
hash("age") = 0
Complexity
When to use
var map = new Dictionary<string, int> {
["apple"] = 3,
["banana"] = 5
};
map["cherry"] = 2; // O(1) add
map["apple"] = 10; // O(1) update
bool has = map.ContainsKey("banana"); // O(1) -> True
map.Remove("cherry"); // O(1)
// Safe lookup
if (map.TryGetValue("apple", out int count))
Console.WriteLine(count); // 10
// Classic interview pattern: Two Sum
int[] TwoSum(int[] nums, int target) {
var seen = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
int need = target - nums[i];
if (seen.TryGetValue(need, out int j))
return new[] { j, i };
seen[nums[i]] = i;
}
return Array.Empty<int>();
}HashSet<T>Unordered collection of unique elements. Uses hashing internally for O(1) membership testing. Supports mathematical set operations like union, intersection, and difference.
hash("age") = 0
Complexity
When to use
var set = new HashSet<int> { 1, 2, 3, 4, 5 };
set.Add(6); // O(1) -> True (added)
set.Add(3); // O(1) -> False (duplicate)
set.Remove(1); // O(1)
bool has = set.Contains(4); // O(1) -> True
// Set operations
var other = new HashSet<int> { 4, 5, 6, 7 };
set.IntersectWith(other); // set = {4, 5, 6}
set.UnionWith(other); // set = {4, 5, 6, 7}
set.ExceptWith(other); // set = {}
// Classic interview pattern: contains duplicate
bool ContainsDuplicate(int[] nums)
=> nums.Length != new HashSet<int>(nums).Count;LinkedList<T>Sequence of nodes where each node points to the next (singly linked) or both next and previous (doubly linked). Efficient insertion and deletion at any known position, but no index-based access.
traversing: 5
Complexity
When to use
var list = new LinkedList<int>();
list.AddLast(10); // O(1)
list.AddLast(20);
list.AddFirst(5); // O(1)
var node = list.Find(20); // O(n) -> LinkedListNode<int>
list.AddBefore(node, 15); // O(1) given node reference
list.Remove(node); // O(1) given node reference
// Iterate
foreach (int val in list)
Console.Write(val + " "); // 5 10 15
// LRU Cache pattern: LinkedList + Dictionary
// Dictionary for O(1) lookup, LinkedList for O(1) reorder
// Move accessed node to front, evict from backSortedSet<T>Collection of unique elements maintained in sorted order, typically backed by a balanced binary search tree (red-black tree). Supports range queries and O(log n) min/max.
search(8)
Complexity
When to use
var sorted = new SortedSet<int> { 5, 3, 8, 1, 9 };
// Internal order: 1, 3, 5, 8, 9 (red-black tree)
sorted.Add(4); // O(log n)
sorted.Remove(3); // O(log n)
bool has = sorted.Contains(8); // O(log n) -> True
int min = sorted.Min; // O(log n) -> 1
int max = sorted.Max; // O(log n) -> 9
// Range query: elements between 4 and 8
var range = sorted.GetViewBetween(4, 8);
foreach (int v in range)
Console.Write(v + " "); // 4 5 8SortedDictionary<K,V>Key-value pairs maintained in sorted key order, typically backed by a balanced BST. Enables ordered iteration and range lookups that hash maps cannot provide.
search(8)
Complexity
When to use
var sd = new SortedDictionary<string, int> {
["banana"] = 2,
["apple"] = 5,
["cherry"] = 1
};
sd["date"] = 3; // O(log n)
// Iterates in sorted key order
foreach (var kvp in sd)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
// apple: 5, banana: 2, cherry: 1, date: 3
// vs SortedList: SortedList uses less memory but
// O(n) insert. SortedDictionary uses O(log n) insert
// but more memory (tree nodes).PriorityQueue<T,P>Collection where elements are dequeued by priority rather than insertion order. Typically implemented as a binary heap. Essential for shortest-path algorithms and top-K problems.
min-heap
Complexity
When to use
// .NET 6+ - min-heap by default
var pq = new PriorityQueue<string, int>();
pq.Enqueue("Low", 3); // O(log n)
pq.Enqueue("Critical", 1);
pq.Enqueue("Medium", 2);
string next = pq.Dequeue(); // O(log n) -> "Critical"
pq.TryPeek(out string top, out int pri); // O(1)
// Classic interview pattern: K closest points
int[][] KClosest(int[][] points, int k) {
var pq = new PriorityQueue<int[], int>();
foreach (var p in points)
pq.Enqueue(p, p[0]*p[0] + p[1]*p[1]);
var result = new int[k][];
for (int i = 0; i < k; i++)
result[i] = pq.Dequeue();
return result;
}ConcurrentDictionary<K,V>Thread-safe hash map designed for concurrent read/write access from multiple threads. Uses fine-grained locking or lock-free techniques instead of a single global lock.
hash("age") = 0
Complexity
When to use
var cache = new ConcurrentDictionary<string, int>();
// Thread-safe atomic operations
cache.TryAdd("hits", 0);
cache.AddOrUpdate("hits", 1, (key, old) => old + 1);
int val = cache.GetOrAdd("sessions", key => {
// Factory only called if key missing
return ExpensiveComputation(key);
});
// Safe enumeration (snapshot semantics)
foreach (var kvp in cache)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
// Parallel-safe counter
Parallel.For(0, 1000, _ =>
cache.AddOrUpdate("count", 1, (k, v) => v + 1));Span<T>Zero-copy view over a contiguous region of memory. Lets you reference a portion of an array or buffer without allocating new memory. Critical for performance-sensitive parsing and processing.
Span[0..3] = [1, 2, 3]
Complexity
When to use
// Zero-copy slice of an array
int[] data = { 1, 2, 3, 4, 5 };
Span<int> slice = data.AsSpan(1, 3); // [2, 3, 4]
slice[0] = 20; // Mutates original: data = {1, 20, 3, 4, 5}
// Zero-allocation string parsing
ReadOnlySpan<char> csv = "Alice,30,Engineer".AsSpan();
int comma1 = csv.IndexOf(',');
ReadOnlySpan<char> name = csv[..comma1]; // "Alice"
// Stack-allocated buffer (no heap, no GC)
Span<byte> buffer = stackalloc byte[256];
buffer[0] = 0xFF;
// Cannot be used in: async methods, class fields,
// lambda captures, or boxed to object.Average-case time complexity. * = amortized.
| Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Dynamic Array | O(1) | O(n) | O(1)* | O(n) |
| Stack | O(n) | O(n) | O(1)* | O(1) |
| Queue | O(n) | O(n) | O(1)* | O(1) |
| Hash Map | O(1) | O(1) | O(1)* | O(1) |
| Hash Set | N/A | O(1) | O(1)* | O(1) |
| Linked List | O(n) | O(n) | O(1) | O(1) |
| Sorted Set | O(n) | O(log n) | O(log n) | O(log n) |
| Sorted Map | O(log n) | O(log n) | O(log n) | O(log n) |
| Priority Queue | O(n) | O(n) | O(log n) | O(log n) |
| Concurrent Map | O(1) | O(1) | O(1)* | O(1) |
| Memory View | O(1) | O(n) | N/A | N/A |
| I need to... | Use |
|---|---|
| Store items by index, resize dynamically | List / Dynamic Array |
| Map keys to values with O(1) lookup | HashMap / Dictionary |
| Track unique items, check existence in O(1) | HashSet / Set |
| Last-in-first-out (undo, DFS, brackets) | Stack |
| First-in-first-out (BFS, task queues) | Queue |
| Keep elements sorted at all times | SortedSet / TreeSet |
| Process items by priority (Dijkstra, top-K) | PriorityQueue / Heap |
| Insert/delete at a known position in O(1) | LinkedList |
| Sorted key-value pairs | SortedDictionary / TreeMap |
| Thread-safe shared cache | ConcurrentDictionary |
| Slice arrays/strings without copying | Span / Slice / memoryview |
The most commonly used are dynamic arrays (List/ArrayList/vector), hash maps (Dictionary/HashMap/dict), and hash sets. For interviews, also know stacks, queues, trees, and priority queues. These cover 90%+ of coding interview problems.
Start with the dynamic array and hash map. Together they solve the majority of interview problems. Then learn stacks (for DFS, bracket matching) and queues (for BFS). After that, tackle trees, heaps, and graphs.
No. Big O measures algorithmic complexity, not language-specific performance. A hash map lookup is O(1) whether you use Python dict, Java HashMap, or C# Dictionary. Constant factors differ (C++ is faster than Python in wall-clock time), but Big O is the same.
Yes, since .NET 6. PriorityQueue<TElement, TPriority> is a min-heap. For a max-heap, negate the priority or use a custom IComparer.
Practice with an AI interviewer that asks you to implement, optimize, and explain data structure choices in real time.
Try a free mock interviewarrow_forward