Deferred Execution
Learn about when LINQ queries are executed.
We'll cover the following
Introduction
There are subtleties regarding the timing of LINQ query execution. There are essentially two ways of executing a LINQ query:
-
Deferred execution: The LINQ query only executes when we try to address an item from a resulting collection.
-
Immediate execution: The LINQ query executes immediately after construction.
Let’s explore these in detail.
Deferred execution
There are three steps to creating and running a LINQ query:
- Creating or attaining a data source
- Creating a query
- Executing the query
Deferred execution means that our query isn’t executed the moment it’s created:
// Step 1. Creating or attaining a data source
var countryList = new List<string>()
{
"Germany", "Thailand", "France", "Spain",
"Italy", "United States", "Romania", "Russia",
"Greece", "Argentina", "Canada", "Mexico",
"Ireland", "Albania", "Slovenia", "Kazakhstan"
};
// Step 2. Creating a query
var countriesThatStartWithC = from country in countryList
where country.StartsWith("C")
select country;
// But the query hasn't run yet!
Rather, the query runs when we want to access an element inside the resulting collection:
// The query is run here and the result is stored in the variable
Console.WriteLine(countriesThatStartWithC[0]); // Canada
To prove that the query doesn’t run until we access an element in the resulting collection, we can try to alter the data source after we construct the query:
Get hands-on with 1400+ tech skills courses.