LINQ Deferred Execution
Talk it through out loud with your AI coach.
The problem
- medium
- Pro
A method builds a LINQ query with Where and Select over an Entity Framework table, then calls Count on it and loops over it. The logs show the database being queried twice. Explain deferred execution, why this happens, and the difference between IEnumerable and IQueryable here.
What a strong answer covers
- When a LINQ query actually does its work.
- Why the database was hit twice and how to avoid it.
- How the two interfaces decide where filtering runs.
- The performance trap of leaving the database too early.
Common mistake: Calling ToList straight after the table and filtering afterwards, which quietly loads the whole table into memory.
Knowing this is half of it. Saying it clearly out loud is the part the coach helps you practise.
Practise it out loud