Data Structures

Intro

A data structure organizes data for efficient access, mutation, and iteration. In .NET, the standard library provides production-ready implementations of the most common structures — List<T>, Dictionary<TKey, TValue>, HashSet<T>, Queue<T>, Stack<T>, LinkedList<T>, SortedSet<T>, and PriorityQueue<TElement, TPriority>. Choosing the right collection usually has a bigger impact on performance than micro-optimizing the code that uses it.

The key decision is matching operations to complexity guarantees: random access by index → array or List<T>; fast lookup by key → Dictionary<TKey, TValue>; membership tests → HashSet<T>; ordered traversal → SortedSet<T> or sorted array; FIFO processing → Queue<T>. Most production performance issues with collections come from using the wrong structure (e.g., searching a List<T> linearly when a HashSet<T> gives O(1) lookups) rather than from the structure's implementation being slow.

Example

var byId = new Dictionary<int, string>
{
    [42] = "Ann"
};

var ordered = new List<string> { "Ann", "Bob" };

Console.WriteLine(byId[42]); // Fast lookup by key
Console.WriteLine(ordered[0]); // Fast lookup by index

Questions


Whats next