Advertisement
Intermediate .NET, Entity Framework Core & Data Access

What is the difference between IQueryable<T> and IEnumerable<T> when writing EF Core queries, and why does it matter for performance?

Short answer

IQueryable represents a composable, not-yet-executed query expression tree that EF Core translates into SQL, meaning additional LINQ operations (Where, OrderBy, Take) chained onto it are incorporated into the actual SQL query sent to the database.

Save .NET mock interview
Advertisement
AModel answer
IQueryable<T> represents a composable, not-yet-executed query expression tree that EF Core translates into SQL, meaning additional LINQ operations (Where, OrderBy, Take) chained onto it are incorporated into the actual SQL query sent to the database. IEnumerable<T> represents an already-materialized in-memory sequence, so calling .AsEnumerable() or accidentally forcing early materialization (like calling .ToList() too early) causes subsequent LINQ operations to execute in application memory instead of the database, often processing far more data than necessary and losing the database's ability to optimize the query (like using indexes).
// Efficient: filtering happens in SQL (WHERE clause)
var expensive = context.Products.Where(p => p.Price > 100).ToList();

// Inefficient: loads ALL products into memory first, THEN filters in C#
var expensive = context.Products.ToList().Where(p => p.Price > 100).ToList();
Real-world example
A performance review catches a query that materializes an entire 500,000-row table into memory via an early .ToList() before applying a filter that should have been part of the SQL WHERE clause, fixed by simply reordering the LINQ chain.
Likely follow-ups
  • How can you tell from code review whether a LINQ chain will execute in SQL or in memory?
  • What operations force premature materialization?
Related topics