wasAsked.

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

Sign in to add your answer

Related interview topics