It’s not just a matter of taste, the choice between .ToList()
and .ToArray()
should be intentional, based on how the resulting collection will be consumed.
If you’ve worked with LINQ in C#, you’ve probably written something like this:
var items = source.Where(x => x.IsValid).ToList();
// or
var items = source.Where(x => x.IsValid).ToArray();
Both materialize the query results immediately, but they behave differently.
The Simple Rule
- Use
.ToList():
If the consumer will modify the collection (add/remove items).
- Use
.ToArray():
If the consumer will only read or mutate existing values without changing the collection size.
Example
// We plan to add/remove elements later
var list = source.Where(x => x.IsValid).ToList();
list.Add(newItem); // works
list.RemoveAt(0); // works
// Array is fixed size, this won't work
var array = source.Where(x => x.IsValid).ToArray();
array.Add(newItem); // compile-time error
Performance Considerations
- For small collections, the performance difference is negligible; pick the one that matches your intent.
- For collections around 10,000+ items, benchmarks have shown that
.ToList()
was slightly faster than .ToArray()
in older .NET versions.
- However, with .NET 9, significant optimizations were made to
.ToArray()
, making it highly efficient even for large datasets.
Next time you materialize a LINQ query, pause and pick the one that aligns with how the collection will actually be used.