Tutorials / Advanced C# and .NET / IEnumerable versus IQueryable

IEnumerable versus IQueryable

14 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

Same methods, different machinery

Both IEnumerable<T> and IQueryable<T> let you write .Where(...) and .Select(...). The code looks identical. What happens underneath is very different, and the difference matters the first time you query a database with Entity Framework Core.

IEnumerable<T> is for objects in memory. Its Where takes a Func<T, bool>, which is compiled code. When you enumerate, it loops over the items and runs that code on each one.

IQueryable<T> is for data sources that can answer queries themselves, such as a SQL database. Its Where takes an Expression<Func<T, bool>>. That is not compiled code. It is a data structure, an expression tree, that describes the lambda. A provider such as EF Core reads the tree and translates it to SQL. The database then does the filtering and sends back only the matching rows.

Seeing the expression tree

The next program needs no database. It shows that the same lambda becomes either code or data depending on the type it is assigned to.

using System.Linq.Expressions;

// As a delegate: compiled code, cannot be inspected
Func<int, bool> asCode = n => n > 5 && n % 2 == 0;

// As an expression: a tree you can read
Expression<Func<int, bool>> asData = n => n > 5 && n % 2 == 0;
Console.WriteLine(asData);                       // n => ((n > 5) AndAlso ((n % 2) == 0))
Console.WriteLine(asData.Body.NodeType);         // AndAlso

// You can still run an expression by compiling it
Func<int, bool> compiled = asData.Compile();
Console.WriteLine(compiled(8));                  // True

// IQueryable over a list: the tree is built, then interpreted in memory
IQueryable<string> names = new List<string> { "Ayesha", "Bilal", "Chand", "Dua" }.AsQueryable();
IQueryable<string> query = names.Where(n => n.Length > 4).OrderBy(n => n);
Console.WriteLine(query.Expression);
Console.WriteLine(string.Join(", ", query));

// The trap: switching to IEnumerable too early
var log = new List<string>();
IEnumerable<int> source = Source(log);
var filteredEarly = source.Where(x => x % 2 == 0).Take(2).ToList();
Console.WriteLine($"Visited {log.Count} items before stopping");

IEnumerable<int> Source(List<string> visited)
{
    for (int i = 1; i <= 1000; i++)
    {
        visited.Add(i.ToString());
        yield return i;
    }
}

Walking through it

The two lambdas have identical text, but they are different things. asCode is a delegate. It runs, and that is all you can do with it. asData is an Expression<Func<int, bool>>. Printing it shows the structure. Its Body is an AndAlso node with two children, and so on down. An EF Core provider walks this tree, finds the property access and the comparison, and writes WHERE Age > 5 AND .... That is how your C# turns into SQL without you writing any SQL.

The compiler picks the version based on the method you call. Calling Where on an IQueryable selects the overload that takes an expression. Calling it on an IEnumerable selects the delegate overload.

The in-memory AsQueryable example shows that query.Expression is the whole chain of calls as a tree. Nothing has run yet. It runs when we enumerate with string.Join. This is deferred execution again, now with a translation step added.

The last block shows lazy sequences stopping early. Source yields up to 1000 numbers, but Take(2) after a Where stops as soon as two even numbers have been found. Only four items are visited. The sequence is pulled one item at a time, not built in full first.

The mistake that costs real money

Imagine this EF Core code:

// Bad: AsEnumerable switches to in-memory LINQ
var expensive = db.Products
    .AsEnumerable()
    .Where(p => p.Price > 1000)
    .ToList();

// Good: the filter becomes part of the SQL
var expensive2 = db.Products
    .Where(p => p.Price > 1000)
    .ToList();

In the bad version, AsEnumerable() turns the query into an IEnumerable. The call to Where now uses the delegate overload. EF Core cannot translate it, so it loads every product into memory and filters afterwards. On a table of a million rows, this is a performance disaster. The same happens if you store a query in an IEnumerable<T> variable or return one from a method, and then add filters.

The reverse problem exists too. If your lambda calls your own method, such as Where(p => MyHelper(p)), EF Core cannot translate it to SQL, because it cannot look inside your method. Modern versions of EF Core throw an exception in that case instead of silently loading everything. That is better, but you still need to know why it happens.

Rules I follow

  • Keep database queries as IQueryable until the last step, then call ToList() or ToListAsync().
  • Filter and project in the database. Fetch only the columns you need with Select.
  • Return a materialised list or a DTO from repository methods, not a half-built IQueryable, unless you intend callers to extend it.
  • Use plain IEnumerable<T> for in-memory work and for method parameters that only need to read a sequence.

Common mistakes

  • Calling AsEnumerable() or ToList() too early and filtering in memory.
  • Using a custom method inside a query that must become SQL.
  • Enumerating an IQueryable twice, which runs two database queries.
  • Returning IQueryable from a service and letting random callers add filters, which makes performance impossible to predict.

Try it yourself

  1. Write an Expression<Func<Product, bool>> for "price above 500 and name starts with K". Print it and read the tree.
  2. Build a reusable filter method that takes an IQueryable<Product> and a minimum price and returns an IQueryable<Product>.
  3. Run the early-stop example with Take(5) and predict how many items are visited. Check your answer.
csharp
using System.Linq.Expressions;

// As a delegate: compiled code, cannot be inspected
Func<int, bool> asCode = n => n > 5 && n % 2 == 0;

// As an expression: a tree you can read
Expression<Func<int, bool>> asData = n => n > 5 && n % 2 == 0;
Console.WriteLine(asData);                       // n => ((n > 5) AndAlso ((n % 2) == 0))
Console.WriteLine(asData.Body.NodeType);         // AndAlso

// You can still run an expression by compiling it
Func<int, bool> compiled = asData.Compile();
Console.WriteLine(compiled(8));                  // True

// IQueryable over a list: the tree is built, then interpreted in memory
IQueryable<string> names = new List<string> { "Ayesha", "Bilal", "Chand", "Dua" }.AsQueryable();
IQueryable<string> query = names.Where(n => n.Length > 4).OrderBy(n => n);
Console.WriteLine(query.Expression);
Console.WriteLine(string.Join(", ", query));

// The trap: switching to IEnumerable too early
var log = new List<string>();
IEnumerable<int> source = Source(log);
var filteredEarly = source.Where(x => x % 2 == 0).Take(2).ToList();
Console.WriteLine($"Visited {log.Count} items before stopping");

IEnumerable<int> Source(List<string> visited)
{
    for (int i = 1; i <= 1000; i++)
    {
        visited.Add(i.ToString());
        yield return i;
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account