Roadmap › LINQ — Language Integrated Query › Module: LINQ Internals and EF Core
Lessons in this course (12)
9. IEnumerable vs IQueryable
Intermediate★ Must knowLesson 9 of 12
IEnumerable<T> | IQueryable<T> | |
|---|---|---|
| Namespace | System.Collections.Generic | System.Linq |
| Lambdas compiled to | Delegates (Func<T,bool>) | Expression trees (Expression<Func<T,bool>>) |
| Execution | In memory (LINQ to Objects) | Translated by a provider (SQL) and run remotely |
| Filtering big tables | Loads everything, filters in RAM | WHERE runs in the database |
| Use | Collections already in memory | EF Core DbSets, remote sources |
csharp
IQueryable<Order> q = db.Orders.Where(o => o.Total > 1000); // nothing sent yet
q = q.OrderBy(o => o.CreatedAt).Take(20); // still composing
Console.WriteLine(q.ToQueryString()); // see the SQL (EF Core 5+)
var list = await q.ToListAsync(); // SELECT TOP(20) ... WHERE Total > 1000 ORDER BY ...
IEnumerable<Order> bad = db.Orders; // as IEnumerable
var slow = bad.Where(o => o.Total > 1000).ToList(); // SELECT * FROM Orders, then filter in memory!