LINQ Interview Question #10

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

LINQ Fundamentals, Syntax, IEnumerable & IQueryable Junior Beginner

Quick Interview Answer

IEnumerable<T> is primarily used for in-memory enumeration, and its LINQ operators execute as .NET code. IQueryable<T> carries an expression tree that a provider can inspect and translate.

Detailed Explanation

IEnumerable<T> is primarily used for in-memory enumeration, and its LINQ operators execute as .NET code. IQueryable<T> carries an expression tree that a provider can inspect and translate.

With a database provider, keeping filtering and projection as IQueryable allows those operations to be translated and executed by the database. Converting to IEnumerable too early can move later processing into application memory.

Code Example

// Database-side filtering
var query = db.Products
    .Where(p => p.Price > 100);

// After materialization, later LINQ is in memory.
var list = await query.ToListAsync();
var names = list.Select(p => p.Name);