Explain the difference between IEnumerable and IQueryable in C#, and show where each belongs in a production API.
Zoho · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, C#, Entity Framework Core
Community answers
Posted by wasAsked editorial collection
`IEnumerable<T>` represents objects enumerated in .NET. LINQ-to-Objects delegates run in the process. `IQueryable<T>` carries an expression tree that a provider, such as EF Core, can translate into another query language. Execution is usually deferred until enumeration or a terminal operation.
```csharp
public async Task<IReadOnlyList<OrderSummary>> SearchAsync(
decimal minimum, CancellationToken ct)
{
return await db.Orders
.AsNoTracking() // IQueryable<Order>
.Where(order => order.Total >= minimum) // translated to SQL
.OrderByDescending(order => order.CreatedAt)
.Select(order => new OrderSummary(order.Id, order.Total))
.Take(50)
.ToListAsync(ct); // executes here
}
```
Calling `AsEnumerable` or `ToList` too early moves later filtering into memory and may fetch far more rows. Conversely, exposing `IQueryable` from an API or across layers leaks provider behavior and lets callers construct unbounded queries. Compose the database query inside the persistence boundary, project only required columns, execute asynchronously, and return a materialized read model.
Prince Yadav · · 0 likes
Both represent sequences you can query with LINQ, but they belong in different layers of a production API.
IEnumerable<T>
- Works on in-memory objects; LINQ operators run as compiled delegates.
- Belongs in business logic, mapping and response shaping after data is loaded, and as the return type of methods that hand finished results to callers.
IQueryable<T>
- Builds an expression tree that EF Core translates into SQL; filtering, sorting, projection and paging execute in the database.
- Belongs inside the data-access code where the query is being composed.
Example of a well-placed query in an API:
public async Task<PagedResult<OrderSummary>> SearchAsync(OrderFilter f, CancellationToken ct)
{
IQueryable<Order> query = _db.Orders.AsNoTracking()
.Where(o => o.TenantId == _tenant.Id);
if (f.Status is not null) query = query.Where(o => o.Status == f.Status);
if (f.From is not null) query = query.Where(o => o.CreatedAt >= f.From);
var total = await query.CountAsync(ct);
var items = await query
.OrderByDescending(o => o.CreatedAt)
.Skip((f.Page - 1) * f.PageSize).Take(f.PageSize)
.Select(o => new OrderSummary(o.Id, o.Customer.Name, o.Total)) // projection in SQL
.ToListAsync(ct);
return new PagedResult<OrderSummary>(items, total); // returns materialised data
}
Everything until ToListAsync is IQueryable, so SQL contains WHERE, ORDER BY, OFFSET/FETCH and only the selected columns. The method returns a finished list, so controllers and other services never accidentally trigger extra queries.
Production guidelines:
- Do not return IQueryable from controllers or public service methods: it moves query execution to unpredictable places, can cause N+1 queries during serialization, and may run after the DbContext is disposed.
- Do not convert to IEnumerable (or call ToList) before filtering, or the whole table is loaded.
- Use AsNoTracking for read-only queries, and projections (Select) to avoid loading unneeded columns.
- Check generated SQL with logging (LogTo or ToQueryString()) during development.