What is the difference between IEnumerable<T> and IQueryable<T> in C#?
Operates in memory. LINQ operators (Where, Select, etc.) are executed on the already-loaded collection using C# delegates.
// Loads ALL users from DB, then filters in C#
IEnumerable<User> users = context.Users.ToList();
var active = users.Where(u => u.IsActive); // filter in memory
Operates on the data source. LINQ operators build an expression tree that is translated into SQL (or another query language) and executed on the database — only the matching rows are returned.
// Translates to: SELECT * FROM Users WHERE IsActive = 1
IQueryable<User> query = context.Users.Where(u => u.IsActive);
var users = await query.ToListAsync(); // SQL runs here
IQueryable<User> query = context.Users;
if (!string.IsNullOrEmpty(search))
query = query.Where(u => u.Name.Contains(search));
if (activeOnly)
query = query.Where(u => u.IsActive);
// Single, efficient SQL query built and executed at the end
var result = await query.OrderBy(u => u.Name).Take(20).ToListAsync();
IQueryable when querying a database — let the DB do the filteringIEnumerable when working with in-memory collections or after ToList()
All Comments