19 November 2026

C# LINQ Deferred Execution and ToList: Student Score Example

  Asp.Net CS By Example       19 November 2026

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.

Query timeline

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

  1. Where creates a query. It has not filtered the list yet.
  2. We add 91 before the first read, so the first result includes 91.
  3. ToList() reads the query immediately and stores those values in a new list called snapshot.
  4. We add 42 after the snapshot. Reading passing again 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

  1. Before running, predict the output if you add 39 instead of 42.
  2. Move ToList() before scores.Add(91). Which values appear in the saved list?
  3. Print passing.Count() before and after adding a score. Unlike Where, 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.

logoblog

Thanks for reading C# LINQ Deferred Execution and ToList: Student Score Example

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.