C# and .NET • Modern C# baseline
LINQ Queries and Deferred Execution
Filter and transform sequences declaratively while understanding when queries execute.
LINQ provides standard operators for filtering, projection, grouping, and aggregation. Many sequence queries use deferred execution: they run when enumerated, not when declared. Re-enumerating a query may repeat work or observe changed data, so materialize results when you need a snapshot.
Key points
- Use ToList or ToArray when a stable materialized result is needed.
- Avoid side effects inside query predicates and projections.
Example
using System.Linq;
int[] values = [3, 10, 7, 12];
var selected = values
.Where(value => value >= 10)
.Select(value => value * value)
.ToArray();
Console.WriteLine(string.Join(", ", selected));
What to expect
100, 144
Practice exercise
Add an OrderBy operation and compare a deferred query with a materialized array.
Key idea: Use LINQ for clear transformations, and be explicit about evaluation and materialization.