Some LINQ queries wait until you read their results. This is called deferred execution. The difference matters when your list changes between creating a query and looping over it. This small student-score example shows the result clearly.
Define Where query → Change scores → Read query → See current values
Create and run the example
First review LINQ filtering for beginners if Where is new to you. Install a supported .NET SDK, create a console project, and replace Program.cs with the complete program below.
dotnet new console -n LinqDeferredScores
cd LinqDeferredScores
List<int> scores = [35, 64, 78];
IEnumerable<int> passing = scores.Where(score => score >= 40);
Console.WriteLine("Query defined");
scores.Add(91);
Console.WriteLine($"First read: {string.Join(", ", passing)}");
List<int> snapshot = passing.ToList();
scores.Add(42);
Console.WriteLine($"Saved list: {string.Join(", ", snapshot)}");
Console.WriteLine($"Fresh read: {string.Join(", ", passing)}");Save the file and run dotnet run.
Expected output
Query defined
First read: 64, 78, 91
Saved list: 64, 78, 91
Fresh read: 64, 78, 91, 42
Why the answers differ
Wherecreates a query. It has not filtered the list yet.- We add 91 before the first read, so the first result includes 91.
ToList()reads the query immediately and stores those values in a new list calledsnapshot.- We add 42 after the snapshot. Reading
passingagain sees 42, but the saved list does not change.
Important detail: ToList() copies the sequence into a new list; if the elements are mutable objects, it does not clone each object. This example uses integers, so the difference is easy to see.
With LINQ to Objects, a deferred query may do its work again each time you enumerate it. If the source is an EF Core database query, repeated enumeration can mean repeated database work. Choose a saved list when you need one stable result, and avoid calling ToList() early when you still need to build the query.
Practice
- Before running, predict the output if you add 39 instead of 42.
- Move
ToList()beforescores.Add(91). Which values appear in the saved list? - Print
passing.Count()before and after adding a score. UnlikeWhere,Count()returns a number immediately.
Next: Learn how IEnumerable<T> differs from IQueryable<T> when querying a database. See Microsoft's LINQ execution guide for the language rules, and the C# tutorial index for related lessons.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.