← Back to list

Deferred Execution in LINQ: What Finally Made It Click

I thought my LINQ query had already run… but it hadn’t.

Monica Laurenzana · 2026-05-05 19:48 · 0 claps · 1.3 min read
#csharp #programming #dotnet #linq #software-development
Open on Medium ↗
Wiki topics: 💻 · Programming

Deferred Execution in LINQ: What Finally Made It Click

I thought my LINQ query had already run… but it hadn’t.

I wrote the query, stepped through my code, and assumed the data was already there.

But what I didn’t realize is that LINQ doesn’t execute right away.

The Part That Confused Me

I thought this code ran immediately:

var users = db.Users.Where(u => u.IsActive);

But nothing actually happened yet.

The Big Idea

What finally made sense to me was this:

LINQ queries don’t execute when they’re defined — they execute when they’re used.

When Does It Actually Run?

It runs when you do something like:

var list = users.ToList();

Or:

foreach (var user in users)
{
    // executes here
}

Why This Matters

This can lead to unexpected behavior.

Example: Data Changes

var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n > 1);
numbers.Add(4);
var result = query.ToList();

Result:

[2, 3, 4]

👉 Even though the query was written earlier, it used the updated data

The Difference That Clicked

I thought LINQ gave me results.

What it actually gives me is:

A query that will run later

Immediate vs Deferred Execution

Deferred (most LINQ)

.Where()
.Select()

👉 runs later

Immediate

.ToList()
.Count()
.First()

👉 runs now

Mental Model That Helped Me

  • Deferred = recipe
  • Immediate = finished meal

Why This Can Cause Bugs

  • data changes before execution
  • multiple enumerations
  • performance issues

Interview Takeaway

Deferred execution means a LINQ query is not executed until the results are enumerated.

Final Thought

This was one of those concepts I thought I understood until I saw how it actually behaves. Once I realized LINQ queries don’t run immediately, a lot of confusing behavior finally made sense.


메타데이터
post_id
b1b4ffc9552a
slug
deferred-execution-in-linq-what-finally-made-it-click-b1b4ffc9552a
url
https://medium.com/@monicalaurenzana/deferred-execution-in-linq-what-finally-made-it-click-b1b4ffc9552a
canonical_url
https://medium.com/@monicalaurenzana/deferred-execution-in-linq-what-finally-made-it-click-b1b4ffc9552a
author_url
https://medium.com/@monicalaurenzana
status
ok
fetched_at
2026-06-18 07:02:39