Mid-level (2-5 years)C#

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

Quick answer

IEnumerable runs the query in memory using delegates, while IQueryable builds an expression tree that a provider such as Entity Framework translates into SQL, so filtering happens in the database.

If you call .Where(...) on an IQueryable<Customer> from Entity Framework, the condition becomes part of the SQL WHERE clause and only matching rows come over the network. If you call it on an IEnumerable<Customer>, all rows are loaded first and then filtered in your application's memory.

A common bug is converting to IEnumerable or calling ToList() too early, which silently loads the full table. Keep the query as IQueryable until you have applied all filtering, sorting and paging, and only then materialise it. Remember that an IQueryable can only contain operations the provider can translate to SQL.

// SQL: SELECT ... WHERE IsActive = 1  (filtered in the database)
var active = dbContext.Customers.Where(c => c.IsActive).ToList();

// loads ALL customers first, then filters in memory
IEnumerable<Customer> all = dbContext.Customers.ToList();
var slow = all.Where(c => c.IsActive).ToList();

Key points

  • IQueryable: expression trees translated to SQL
  • IEnumerable: in-memory iteration with delegates
  • Materialise (ToList) as late as possible