Data Structures in C#

12 essential data structures for C# developers. Each one explained with Big O complexity, animated visuals, and real code samples you can copy.

Array

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.

7
3
9
1
5
[0]
[1]
[2]
[3]
[4]

arr[0] = 7

Complexity

Access by indexO(1)
SearchO(n)
Insert / DeleteO(n)

When to use

  • +You know the exact size at creation time
  • +You need the fastest possible index-based access
  • +Working with fixed-length data like matrices or buffers
C#
// 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)

Dynamic Array

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.

7
3
9
1
5
[0]
[1]
[2]
[3]
[4]

arr[0] = 7

Complexity

Access by indexO(1)
SearchO(n)
AppendO(1)*
Insert / Remove (middle)O(n)

When to use

  • +You need a resizable collection (most common case)
  • +You frequently access elements by index
  • +You mostly add or remove at the end
C#
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

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.

arrow_downward top
10

Push 10

Complexity

PushO(1)
PopO(1)
PeekO(1)
SearchO(n)

When to use

  • +Undo/redo functionality
  • +Expression parsing and evaluation
  • +DFS traversal of trees and graphs
  • +Matching brackets, parentheses validation
C#
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

Queue<T>

First-In-First-Out (FIFO) collection. Elements are added at the back and removed from the front. Fundamental for breadth-first processing.

front
10
back

Enqueue 10

Complexity

EnqueueO(1)
DequeueO(1)
PeekO(1)
SearchO(n)

When to use

  • +BFS traversal of trees and graphs
  • +Task scheduling and job queues
  • +Message passing between components
  • +Rate limiting, buffering
C#
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);
    }
}

Hash Map

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.

0
age:30
1
2
name:Al
3
city:NY

hash("age") = 0

Complexity

InsertO(1)*
LookupO(1)
DeleteO(1)
Contains keyO(1)

When to use

  • +Two Sum and frequency counting patterns
  • +Caching computed results (memoization)
  • +Grouping data by a key
  • +Any problem requiring O(1) lookup by key
C#
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>();
}

Hash Set

HashSet<T>

Unordered collection of unique elements. Uses hashing internally for O(1) membership testing. Supports mathematical set operations like union, intersection, and difference.

0
age:30
1
2
name:Al
3
city:NY

hash("age") = 0

Complexity

AddO(1)*
ContainsO(1)
RemoveO(1)
Union / IntersectO(n)

When to use

  • +Checking if an element exists in O(1)
  • +Removing duplicates from a collection
  • +Set operations: union, intersection, difference
  • +Visited tracking in graph traversal
C#
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;

Linked List

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.

5
12
8
20

traversing: 5

Complexity

Insert at head/tailO(1)
Remove (given node)O(1)
SearchO(n)
Access by indexO(n)

When to use

  • +Frequent insertion/deletion in the middle
  • +Implementing LRU cache (with a hash map)
  • +When you need a deque (double-ended queue)
  • +Problems involving pointer manipulation
C#
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 back

Sorted Set (BST)

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

831215

search(8)

Complexity

AddO(log n)
ContainsO(log n)
RemoveO(log n)
Min / MaxO(log n)

When to use

  • +Maintaining a sorted collection of unique items
  • +Range queries (all elements between X and Y)
  • +Sliding window problems needing sorted order
  • +Leaderboards, ranking systems
C#
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 8

Sorted Map (BST)

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

831215

search(8)

Complexity

InsertO(log n)
LookupO(log n)
RemoveO(log n)
Iterate (sorted)O(n)

When to use

  • +You need sorted key-value pairs
  • +Ordered iteration over entries
  • +Range lookups by key
  • +When insertion order or sorted order matters
C#
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).

Priority Queue (Heap)

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.

13579

min-heap

Complexity

InsertO(log n)
Extract min/maxO(log n)
PeekO(1)
SearchO(n)

When to use

  • +Dijkstra's shortest path algorithm
  • +Merge K sorted lists/streams
  • +Top-K / Kth largest element problems
  • +Event-driven simulation, scheduling
C#
// .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;
}

Concurrent Hash Map

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.

0
age:30
1
2
name:Al
3
city:NY

hash("age") = 0

Complexity

InsertO(1)*
LookupO(1)
DeleteO(1)
Atomic updateO(1)*

When to use

  • +Multi-threaded caching
  • +Shared state across threads or async tasks
  • +Producer-consumer patterns with keyed data
  • +When you need concurrent reads and writes
C#
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));

Memory View / Slice

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.

1
2
3
4
5
6

Span[0..3] = [1, 2, 3]

Complexity

Create sliceO(1)
Access by indexO(1)
SearchO(n)
CopyO(n)

When to use

  • +Parsing strings or binary data without copies
  • +Processing sub-arrays without allocation
  • +High-performance, zero-allocation code paths
  • +Interop with native or unmanaged memory
C#
// 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.

Big O Comparison

Average-case time complexity. * = amortized.

StructureAccessSearchInsertDelete
ArrayO(1)O(n)O(n)O(n)
Dynamic ArrayO(1)O(n)O(1)*O(n)
StackO(n)O(n)O(1)*O(1)
QueueO(n)O(n)O(1)*O(1)
Hash MapO(1)O(1)O(1)*O(1)
Hash SetN/AO(1)O(1)*O(1)
Linked ListO(n)O(n)O(1)O(1)
Sorted SetO(n)O(log n)O(log n)O(log n)
Sorted MapO(log n)O(log n)O(log n)O(log n)
Priority QueueO(n)O(n)O(log n)O(log n)
Concurrent MapO(1)O(1)O(1)*O(1)
Memory ViewO(1)O(n)N/AN/A

Which collection should I use?

I need to...Use
Store items by index, resize dynamicallyList / Dynamic Array
Map keys to values with O(1) lookupHashMap / 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 timesSortedSet / TreeSet
Process items by priority (Dijkstra, top-K)PriorityQueue / Heap
Insert/delete at a known position in O(1)LinkedList
Sorted key-value pairsSortedDictionary / TreeMap
Thread-safe shared cacheConcurrentDictionary
Slice arrays/strings without copyingSpan / Slice / memoryview

Frequently Asked Questions

What are the most important data structures in C#?add

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.

Which C# data structure should I learn first?add

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.

Does Big O complexity change between languages?add

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.

Is there a built-in priority queue in C#?add

Yes, since .NET 6. PriorityQueue<TElement, TPriority> is a min-heap. For a max-heap, negate the priority or use a custom IComparer.

Know the structures.
Now use them under pressure.

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