Choosing the right collection is one of the highest-leverage decisions in everyday C#. A membership test on a List checks every element; the same test on a HashSet is one hash lookup. On large data that is the difference between a page that loads and one that times out. This guide covers what to use when, and the mistakes that produce runtime exceptions.
Choosing#
| You need | Use | Lookup cost |
|---|---|---|
| Ordered, index access | List<T> |
by index instant, by value linear |
| Key to value | Dictionary<K,V> |
constant |
| Unique values, membership tests | HashSet<T> |
constant |
| Sorted keys | SortedDictionary<K,V> |
logarithmic |
| First in, first out | Queue<T> |
— |
| Last in, first out | Stack<T> |
— |
| Fixed size, known at creation | T[] |
by index instant |
| Shared between threads | ConcurrentDictionary<K,V> |
constant |
A habit worth forming: declare the interface, construct the implementation.
IList<string> names = new List<string>();
IDictionary<string, int> ages = new Dictionary<string, int>();
// For parameters, be as general as you can
void Process(IEnumerable<Order> orders) { }
A method taking IEnumerable<T> works with arrays, lists and LINQ results alike.
List#
var names = new List<string> { "Ana", "Sam" };
names.Add("Kim");
names.Insert(0, "Zoe");
names.Remove("Sam");
names.RemoveAt(0);
names.RemoveAll(n => n.StartsWith("A"));
names[0]; // by index
names.Count;
names.Contains("Kim"); // walks the list
names.IndexOf("Kim");
names.Sort();
names.Sort((a, b) => b.CompareTo(a));
// Size it up front when you know roughly how many
var orders = new List<Order>(expectedCount);
A List grows by allocating a larger array and copying. Giving it a capacity avoids repeating that as it fills.
Dictionary#
var ages = new Dictionary<string, int>
{
["Ana"] = 34,
["Sam"] = 28,
};
// The idiomatic lookup
if (ages.TryGetValue("Ana", out int age))
{
Console.WriteLine(age);
}
ages.TryAdd("Kim", 30); // no exception if present
ages["Kim"] = 31; // add or update
ages.Remove("Sam");
ages.ContainsKey("Ana");
foreach (var (name, value) in ages)
{
Console.WriteLine($"{name} {value}");
}
int value = ages.GetValueOrDefault("Kim", 0);
// Counting
counts[word] = counts.GetValueOrDefault(word) + 1;
// Grouping
if (!groups.TryGetValue(city, out var list))
{
list = new List<Order>();
groups[city] = list;
}
list.Add(order);
Or let LINQ do the grouping for you:
var byCity = orders.GroupBy(o => o.City)
.ToDictionary(g => g.Key, g => g.ToList());
HashSet#
var tags = new HashSet<string> { "csharp", "dotnet" };
tags.Add("csharp"); // returns false - already present
tags.Contains("dotnet"); // one hash lookup
// Set operations
var a = new HashSet<int> { 1, 2, 3, 4 };
var b = new HashSet<int> { 3, 4, 5 };
a.IntersectWith(b); // a becomes { 3, 4 }
a.UnionWith(b);
a.ExceptWith(b);
a.SymmetricExceptWith(b);
The reason to reach for a set is the membership test:
// Slow: checks every entry, for every word
var blocked = new List<string>(fiftyThousandWords);
foreach (var word in message)
if (blocked.Contains(word)) { }
// Fast: one hash lookup each
var blockedSet = new HashSet<string>(fiftyThousandWords);
foreach (var word in message)
if (blockedSet.Contains(word)) { }
Converting the list to a set once, outside the loop, is frequently the largest single performance improvement available in a piece of C#.
Queue and Stack#
var queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
queue.Dequeue(); // "first"
queue.TryDequeue(out var next); // no exception when empty
queue.Peek();
var stack = new Stack<string>();
stack.Push("a");
stack.Pop(); // "a"
stack.TryPop(out var top);
// Both ends
var deque = new LinkedList<string>();
deque.AddFirst("a");
deque.AddLast("b");
Prefer the Try methods. Dequeue and Pop throw on an empty collection, which is rarely what you want in a loop.
Read-only views#
public class Basket
{
private readonly List<Item> _items = new();
public IReadOnlyList<Item> Items => _items; // callers cannot add
public void Add(Item item) => _items.Add(item);
}
// Genuinely immutable
var fixedList = ImmutableList.Create("a", "b");
var frozen = someDictionary.ToFrozenDictionary(); // fast reads, no writes
IReadOnlyList is a view: the caller cannot modify it, but the owner still can and the caller sees those changes. ImmutableList genuinely cannot change. Choose based on whether you need to prevent modification or to guarantee stability.
Modifying while iterating#
foreach (var name in names)
{
if (name.StartsWith("A")) names.Remove(name); // throws
}
InvalidOperationException: Collection was modified; enumeration operation may not execute.
Three correct alternatives:
// 1. RemoveAll - clearest
names.RemoveAll(n => n.StartsWith("A"));
// 2. Loop backwards by index
for (int i = names.Count - 1; i >= 0; i--)
if (names[i].StartsWith("A")) names.RemoveAt(i);
// 3. Build a new collection
names = names.Where(n => !n.StartsWith("A")).ToList();
For a dictionary, collect the keys first:
foreach (var key in ages.Keys.ToList())
{
if (ages[key] < 18) ages.Remove(key);
}
Custom types as keys#
public class Point
{
public int X { get; init; }
public int Y { get; init; }
}
var set = new HashSet<Point>();
set.Add(new Point { X = 1, Y = 2 });
set.Add(new Point { X = 1, Y = 2 });
Console.WriteLine(set.Count); // 2 - not what you wanted
Without an override, equality is reference identity. Implement both Equals and GetHashCode, always together — or use a record, which does it for you:
public record Point(int X, int Y);
var set = new HashSet<Point> { new(1, 2), new(1, 2) };
Console.WriteLine(set.Count); // 1
Collection expressions#
// C# 12
List<int> numbers = [1, 2, 3];
int[] array = [1, 2, 3];
Span<int> span = [1, 2, 3];
int[] combined = [..first, ..second, 99];
A single syntax for creating any collection type, with spread support. Worth adopting in new code.
Questions people ask#
Array or List?
An array when the size is fixed and known, or in performance-critical code. A List everywhere else — it grows, and its API is more useful.
Is Dictionary ordered?
No, and you must not rely on the order you observe. Use SortedDictionary for sorted keys, or order explicitly with LINQ when you enumerate.
What is the difference between IEnumerable and ICollection?
IEnumerable only supports iteration. ICollection adds Count, Add and Remove. IList adds index access. Accept the least capable one your method actually needs.
When should I use ConcurrentDictionary?
When several threads read and write the same dictionary. Wrapping a plain Dictionary in a lock works but is slower and easier to get wrong.
Where to go next#
- C# generics — the type system these are built on.
- C# performance optimization — where collection choice pays.
- Advanced data structures — the ideas underneath.