The short answer: IQueryable builds a query that a provider (usually Entity Framework Core) runs in the database; IEnumerable runs LINQ over objects that are already in memory. Key differences: - Namespace: IEnumerable<T> is in System.Collections.Generic; IQueryable<T> is in System.Linq and inherits from IEnumerable<T>. - Execution: IEnumerable LINQ methods take delegates (Func<T,bool>) and execute in .NET. IQueryable methods take expression trees (Expression<Func<T,bool>>) that the provider translates, for example into SQL. - Data transfer: with IQueryable only the filtered rows come back; with IEnumerable over a DbSet, rows are loaded first and filtered afterwards. - Best for: IQueryable for remote data sources (databases, OData); IEnumerable for in-memory collections such as List<T> or arrays. A typical interview trap: public IEnumerable<Customer> GetCustomers() => _db.Customers; // returns IEnumerable var vip = repo.GetCustomers().Where(c => c.IsVip).ToList(); Because the method's return type is IEnumerable, the Where runs in memory after every customer has been read. Returning IQueryable (or, better, applying the filter inside the repository) lets EF generate WHERE IsVip = 1. Both types are lazy (deferred execution): the query only runs when you enumerate it with foreach, ToList, First or Count. Enumerating an IQueryable twice runs the SQL twice, so materialise once if you need the results repeatedly. One caution: not every C# expression can be translated. Calling your own helper method inside an IQueryable Where may throw a translation error in EF Core; move that logic after AsEnumerable() or rewrite it in translatable terms.
Ravindra Wadile · · 0 likes