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

[!QUESTION]- How do you choose between List, Dictionary<TKey, TValue>, and HashSet?
Use List<T> when you need ordered, index-based access and the primary operations are iteration or positional lookup. Use Dictionary<TKey, TValue> when you need fast lookup, insertion, and deletion by a unique key. Use HashSet<T> when you only need membership testing and set operations (union, intersection, difference) without associated values.
The wrong choice shows up as O(n) scans that should be O(1) lookups. [!QUESTION]- When would you use LinkedList over List in .NET?
Almost never in practice. List<T> (backed by a contiguous array) has better cache locality, lower memory overhead per element, and faster iteration. LinkedList<T> only wins when you need frequent insertions/deletions in the middle of a very large collection and already hold a reference to the node.
In most .NET code, List<T> is the correct default.
Whats next

Parent
02 Computer Science

Pages