C# LINQ Mastery: From Fundamentals to High-Performance Queries
What You Will Master in This Tutorial
- Understand the mechanics of deferred vs. immediate query execution.
- Write clean, declarative queries using method syntax and query comprehension syntax.
- Avoid common memory allocation traps like multiple enumeration (CA1851).
- Benchmark LINQ queries against native Span<T> and imperative loops.
1. Understanding Deferred Execution Mechanics
Language Integrated Query (LINQ) is one of the most powerful paradigms introduced into C#. At its core, LINQ relies on deferred execution. When you write a LINQ query expression containing Where, Select, or Take, the runtime does not execute the filtering or transformation immediately. Instead, it constructs an expression tree or an enumerator state machine.
CSHARP
// Query is defined but NOT executed yet
IEnumerable<int> numbers = Enumerable.Range(1, 1000);
var query = numbers.Where(n => {
Console.WriteLine($"Evaluating: {n}");
return n % 2 == 0;
}).Take(3);
Console.WriteLine("Starting enumeration...");
// Execution happens lazily on-demand here:
foreach (var n in query) {
Console.WriteLine($"Received: {n}");
}
Note: Crucial Tip: Beware of multiple enumerations. If you iterate over query twice, the lambda filters will re-execute both times unless you materialize the sequence using .ToList() or .ToArray().
Advertisement
Cloud Infrastructure & High-Performance Dev Environments
Knowledge Check: Test Your Understanding
1. What happens when you call .Where(...) on an IEnumerable<T>?
Frequently Asked Questions
Is LINQ slower than a standard for loop in C#?
In microbenchmarks, imperative for loops can be faster due to eliminating delegate invoke overhead. However, in modern .NET 8 and .NET 9, the JIT compiler includes extensive LINQ inlining and vectorization.