MediumConcept

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

Technology:
C#
Experience:
Mid-level,
Senior

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.

Detailed explanation

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.

Example

csharp
// 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
  • C#Medium

    What is LINQ in C# and what is deferred execution?

    LINQ (Language Integrated Query) lets you query collections, databases and XML with a consistent syntax, and deferred execution means a query does not run when you define it but when you enumerate the results.

    Junior 路 Mid-level 路 Functions & Scope
  • C#Easy

    What is the difference between string and StringBuilder in C#?

    A string is immutable, so every change creates a new string object, while StringBuilder is a mutable buffer that modifies its contents in place, making it much faster for repeated concatenation.

    Intern 路 Junior 路 Performance
  • C#Easy

    What is the difference between const and readonly in C#?

    A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.

    Junior 路 Mid-level 路 Programming Fundamentals