C# Interview Question #39

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

Generics & Collections Mid-Level Intermediate

Quick Interview Answer

IEnumerable<T> represents an enumerable sequence and its LINQ operations normally execute as .NET code over objects.

Detailed Explanation

IEnumerable<T> represents an enumerable sequence and its LINQ operations normally execute as .NET code over objects.

IQueryable<T> represents a query that a provider can translate into another query language. In Entity Framework Core, IQueryable<T> expressions are typically translated into SQL and executed by the database.

This distinction is important for performance. Applying Where, Select, OrderBy, Skip, and Take while the query remains IQueryable can allow filtering, projection, sorting, and pagination to occur in SQL before data is transferred to the application.

Calling ToList, AsEnumerable, or another materialization/boundary operation changes how subsequent processing occurs, so database queries should be composed carefully.

Code Example

IQueryable<Product> query = context.Products
    .Where(p => p.IsActive)
    .OrderBy(p => p.Name);

List<Product> products = await query
    .Take(20)
    .ToListAsync();