wasAsked.

IEnumerable vs IQueryable

HCA Healthcare · Role not specified · technical

Published

Year not specified · .NET, C#

Community answers

Posted by wasAsked editorial collection

IEnumerable<T> represents objects enumerated in .NET; its LINQ delegates run in the process. IQueryable<T> carries an expression tree that a provider such as EF Core can translate to SQL. Example: var rows = await db.Orders .Where(x => x.Total >= minimum) .OrderByDescending(x => x.CreatedAt) .Select(x => new OrderDto(x.Id, x.Total)) .Take(50).ToListAsync(ct); Calling ToList or AsEnumerable too early moves later filtering into memory. Do not expose IQueryable across an API boundary. Compose and execute a bounded query inside the persistence layer, project only required columns, and return materialized DTOs.

Backbencher Developer · · 0 likes

IEnumerable and IQueryable look similar because both support LINQ, but they execute queries in different places. IEnumerable<T> - For collections in memory (List, arrays, results already fetched). - LINQ to Objects: Where, Select and similar take normal delegates and run in your process. - Good for small data or for processing results after the database query has finished. IQueryable<T> - For remote data sources, mainly databases through Entity Framework Core. - Builds an expression tree; the provider translates it into SQL when the query is executed. - Filtering, sorting, grouping and paging happen on the database server, so only the needed rows are returned. Example with EF Core: IQueryable<Employee> q = db.Employees.Where(e => e.DepartmentId == 5); var top = await q.OrderBy(e => e.Name).Take(10).ToListAsync(); // SELECT TOP(10) ... WHERE DepartmentId = 5 ORDER BY Name IEnumerable<Employee> e = db.Employees.AsEnumerable(); var top2 = e.Where(x => x.DepartmentId == 5).Take(10).ToList(); // SELECT * FROM Employees, then filtered in memory Things to mention in an interview: - Both are lazy: the query runs only when you iterate or call ToList, Count, First and so on. - IQueryable<T> inherits from IEnumerable<T>, so an IQueryable can be passed where IEnumerable is expected — and that silently switches later operators to in-memory execution. - Not all C# can be translated to SQL; unsupported methods inside IQueryable expressions cause runtime errors in EF Core. - Performance impact: misuse of IEnumerable over a DbSet is a common cause of slow APIs and high memory usage. Rule: compose and filter with IQueryable inside the data layer; return materialised results (List or IReadOnlyList) to the rest of the app.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics