What is the difference between IEnumerable and IQueryable in C#?

What is the difference between IEnumerable and IQueryable in C#?

What is the difference between IEnumerable and IQueryable in C#?

Question

What is the difference between IEnumerable<T> and IQueryable<T> in C#?

Answer

IEnumerable<T>

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

IQueryable<T>

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

Composing Queries

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();

Rule of Thumb

  • Use IQueryable when querying a database — let the DB do the filtering
  • Use IEnumerable when working with in-memory collections or after ToList()
All Comments