In C# LINQ, how do ToList(), ToArray() and ToHashSet() differ when materialising a query, and what does each result share with the source?
answer
- one pass, results stored
- growable versus fixed length
- duplicates decided by a comparer
- references copied, objects shared
basics
~20 sAll three enumerate the query once and store the results: ToList() in a growable List<T>, ToArray() in a fixed-length array, ToHashSet() in a HashSet<T> without duplicates. Later source rows are absent, but changes to shared element objects show through.
solid answer
~40 sMaterialising runs the pipeline **once, immediately**, and keeps the output, so later reads are cheap and repeatable. `ToList()` returns a `List<T>`: indexable and growable, right when the caller adds or removes. `ToArray()` returns a `T[]`: indexable, fixed length, a natural fit for read-only use. `ToHashSet()` returns a `HashSet<T>` that keeps one element per value under `EqualityComparer<T>.Default` or a comparer you pass, for fast `Contains`, and promises no order. All three are **snapshots of membership, not deep copies**: rows added to the source afterwards are missing, but reference-type elements are the same objects, so a property changed on an `Order` shows through the snapshot, even if that order no longer matches the filter.
code
csharp · 22 linesvar orders = new List<Order> { new(1, "ada", 250m), new(2, "lin", 900m), new(3, "ada", 700m) };
var large = orders.Where(o => o.Total > 500m);
List<Order> asList = large.ToList(); // growable List<Order>
Order[] asArray = large.ToArray(); // fixed-length Order[]
HashSet<string> customers = orders.Select(o => o.Customer).ToHashSet();
orders.Add(new Order(4, "kim", 800m)); // later rows: not in any snapshot
orders[1].Total = 50m; // same Order object: visible through every snapshot
Console.WriteLine($"query {large.Count()}, list {asList.Count}, array {asArray.Length}");
Console.WriteLine($"list[0].Total = {asList[0].Total}");
Console.WriteLine($"distinct customers: {customers.Count}");
asList.Add(new Order(5, "max", 999m)); // a List<T> can grow; an array cannot
Console.WriteLine($"list after Add: {asList.Count}");
class Order(int id, string customer, decimal total)
{
public int Id { get; } = id;
public string Customer { get; } = customer;
public decimal Total { get; set; } = total;
}go deeper
Recall that ToList() and ToArray() run the query right away and store the results, so the result stops changing when the source does.
Explain the container each call returns, how ToHashSet() decides duplicates, and why mutated element objects still show through a snapshot.
Choose the container by how the result is used, spot needless defensive copies, and recognise snapshots that hold objects which no longer match their filter.
Decide whether results a team passes around must be immutable as well as materialised, since copying references alone does not freeze the data.
## Materialising is an immediate operation A deferred LINQ to Objects query re-runs its pipeline on every enumeration. **Materialising** means running it once and storing the elements in a real collection. `ToList()`, `ToArray()`, `ToHashSet()`, `ToDictionary()` and `ToLookup()` are all **immediate** operators: when you call them, they enumerate the source to the end, apply every `Where`, `Select` and other stage in the chain, and return a filled container. From then on, reading the container does not touch the query's lambdas. A C# 12 collection expression with a spread, such as `List<Order> snapshot = [.. query];`, materialises the same way: the query is enumerated once, on that line, into the target type. ## Three containers | Call | Returns | Length | Duplicates | Typical use | |---|---|---|---|---| | `ToList()` | `List<T>` | growable (`Add`, `Remove`, `Insert`) | kept | the caller will modify the result, or wants `List<T>` methods | | `ToArray()` | `T[]` | fixed | kept | read-only use, interop, APIs that take arrays | | `ToHashSet()` | `HashSet<T>` | growable | removed by the comparer | fast membership tests with `Contains`, de-duplication | A few details worth stating precisely: - Both `ToList()` and `ToArray()` **preserve the order** in which the query produced elements, and both offer O(1) indexing. - `ToHashSet()` decides duplicates with `EqualityComparer<T>.Default` unless you pass an `IEqualityComparer<T>`; for a class without overridden equality that means reference identity. A set does not promise any enumeration order. - For a source that already implements `ICollection<T>`, such as a `List<T>`, both `ToList()` and `ToArray()` allocate a new container of the exact size and copy into it. **Calling `ToList()` on a list still copies it.** - For a source of unknown length, the implementation grows an internal buffer while it reads and then produces the result. ## A snapshot of membership, not of objects The example below materialises the same filtered query three ways and then changes the source. 1. `large.ToList()` and `large.ToArray()` both hold **2** orders (900 and 700). 2. An order of 800 is **added** to `orders`. The live query now counts it, but neither snapshot does: they stopped reading when they were built. 3. The 900 order's `Total` is **set to 50**. The snapshot's first element now reports **50**, because the list stores a reference to the same `Order` object, not a copy. The snapshot now holds an order that no longer passes the filter it was built with. 4. `ToHashSet()` over customer names holds **2** distinct names, because the duplicate "ada" was dropped. 5. `asList.Add(...)` grows the list to **3**; an array has no such operation. The rule to remember: materialising copies **references** for reference types (and copies **values** for value types such as `int` or a struct). Whether a later change is visible depends on whether it changes the source collection (not visible) or an object both collections point to (visible). ## Choosing one - Pick **`ToList()`** when the result will be modified, or when code downstream expects `List<T>`. - Pick **`ToArray()`** when the result is fixed once built and only read or indexed. - Pick **`ToHashSet()`** when the next step is many `Contains` checks or the goal is de-duplication; decide the comparer explicitly for strings or custom types. - Use `ToDictionary()` for keyed lookup of one element per key; one-to-many lookups belong to the grouping operators. ## Costs to weigh - Each call allocates a container holding every element; a million-row query means a million-slot array or list. - Materialising inside a loop, for example calling `ToList()` on the same query once per iteration, repeats the whole pipeline and the allocation every time; hoist it out of the loop. - Materialising removes streaming: the whole result must exist before the first item is used. - Defensive `ToList()` calls on data that is already a list add a copy each time without changing behaviour. - If elements must not change underneath the snapshot, the elements themselves have to be immutable, such as records with init-only properties, or be cloned; no `To...` call does that. ## Summary - `ToList()`, `ToArray()` and `ToHashSet()` run the query once, on the spot, and store the output. - They differ in container: growable list, fixed array, de-duplicating set. - None is a deep copy: new source rows are absent, but shared objects are shared.
- Does calling ToList() on something that is already a List<T> return the same list?No. `ToList()` always returns a new `List<T>`; for an `ICollection<T>` source it allocates one of the exact size and copies the elements in. That makes it a valid defensive copy when the original will keep changing, but it is an O(n) allocation, so calling it on data that is already a private list just to be safe costs memory without changing behaviour.
- Is `List<Order> snapshot = [.. query];` deferred or immediate?Immediate. A collection expression with a spread element, available since C# 12, enumerates the query once on that line and fills a new `List<Order>`. Rows added to the source afterwards are not in it, exactly as with `ToList()`. The spread form is handy when the target type is declared and several sources are combined into one collection.
- ToList() deep-copies the orders, so later edits to an order do not show
- A materialised list updates itself when rows are added to the source
- ToArray() keeps the query live and re-runs it when indexed
- ToHashSet() keeps duplicates and preserves insertion order
- ToList() on a List<T> returns the same instance at no cost