LESSON 11 OF 19

When ToList Is Called Too Early: The Mistake of Executing LINQ in Memory

Learn when ToList executes a query, how IQueryable differs from IEnumerable, and why filtering and projection should usually remain before ToList.

35 dk 98

Introduction

One of the most common performance mistakes when using Entity Framework Core and LINQ is calling ToList or ToListAsync too early. The code may produce the correct result, but once the query is materialized, later filtering, sorting and projection are performed in application memory instead of in the database.

This may be invisible with a small development dataset. In production, however, loading hundreds of thousands of rows into memory can increase network traffic, query time, application memory usage and CPU consumption. In this lesson, we will examine how Where, Select, OrderBy and ToList affect execution timing and compare the performance consequences of moving from IQueryable to IEnumerable.

1. Deferred execution and the actual execution point

In EF Core, a DbSet<T> normally behaves as an IQueryable<T>. Instead of executing immediately, it builds an expression tree that can be translated by a query provider. Methods such as Where, Select and OrderBy generally compose the query. Database access occurs when the query is enumerated or when a terminal operation requests a result.

Methods such as ToList, ToArray, First, Single, Any and Count execute a query. In asynchronous code, use their database-executing counterparts such as ToListAsync, FirstAsync, SingleAsync, AnyAsync and CountAsync.

var query = context.Products
    .Where(p => p.IsActive)
    .OrderBy(p => p.Name);

// No database query has been sent yet.

var products = await query.ToListAsync();
// The query executes here.

In this example, the filter and ordering remain part of the database query. EF Core attempts to translate the LINQ expression into SQL supported by the selected provider, so only the required rows are returned.

2. The mistake: materializing too early

The following code works, but the call to ToListAsync loads every product before filtering.

var allProducts = await context.Products.ToListAsync();

var result = allProducts
    .Where(p => p.IsActive && p.StockQuantity > 0)
    .OrderBy(p => p.Name)
    .Select(p => new ProductListItem
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .ToList();

The first line sends a query with the approximate meaning shown below:

SELECT Id, Name, Price, IsActive, StockQuantity, ...
FROM Products;

The later Where, OrderBy and Select calls are now LINQ-to-Objects operations over a List<Product>. Filtering therefore happens in the application rather than in the database. Unnecessary rows have already crossed the network and have been materialized as objects.

3. The corrected version: keep operations before ToList

The preferred approach is to complete database-translatable operations before calling ToListAsync.

var result = await context.Products
    .Where(p => p.IsActive && p.StockQuantity > 0)
    .OrderBy(p => p.Name)
    .Select(p => new ProductListItem
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .ToListAsync();

EF Core can translate the filtering, ordering and projection in this version into SQL. The database selects only active products that are in stock and returns only the three requested columns.

SELECT Id, Name, Price
FROM Products
WHERE IsActive = 1 AND StockQuantity > 0
ORDER BY Name;

The exact SQL depends on the provider and database engine. The important point is that unnecessary rows and columns are not sent to the application. For list screens, projecting into a DTO or anonymous type often reduces network and memory costs compared with loading complete entities.

4. IQueryable and IEnumerable

IQueryable<T> represents a query that can be translated and executed by a provider. With EF Core, the provider attempts to translate the expression tree into SQL. IEnumerable<T> represents an enumerable sequence that is processed through in-memory LINQ operations.

IQueryable<Product> query = context.Products;

query = query.Where(p => p.IsActive);
query = query.OrderBy(p => p.Name);

var products = await query.ToListAsync();

The filtering and ordering above are included in the database query. After ToListAsync, however, the value is a materialized list:

var products = await context.Products
    .Where(p => p.IsActive)
    .ToListAsync();

var filtered = products
    .Where(p => p.StockQuantity > 0)
    .OrderBy(p => p.Name)
    .ToList();

The second filter and ordering run in memory. This can be intentional when a small result set must be processed by a .NET method that cannot be translated to SQL. In that situation, an explicit client-side transition can be made with AsEnumerable.

var products = await context.Products
    .Where(p => p.IsActive)
    .Select(p => new ProductListItem
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .AsEnumerable()
    .Where(p => NormalizeName(p.Name).Contains("pro"))
    .ToList();

Here, the active-product filter and projection are executed by the database. The custom method after AsEnumerable runs in memory. Even so, if the first filter is not selective, many rows may still be transferred. Client-side evaluation should therefore be used only after considering the result size and the absence of a practical server-side alternative.

5. ToList and AsEnumerable are not equivalent

ToList executes the query immediately and stores all results in a list. AsEnumerable changes how the source is viewed and does not itself create a list containing every result. Enumeration still begins when the sequence is consumed.

var query = context.Products
    .Where(p => p.IsActive)
    .AsEnumerable();

var firstTen = query
    .Take(10)
    .ToList();

In this example, Where remains before the client-side boundary. However, Take(10) is now the IEnumerable operator. Depending on provider behavior and query execution, matching rows may be read before the first ten are selected in memory. Database-translatable operators such as Take should normally remain before AsEnumerable.

var firstTen = await context.Products
    .Where(p => p.IsActive)
    .OrderBy(p => p.Name)
    .Take(10)
    .AsNoTracking()
    .ToListAsync();

This form applies filtering, ordering and limiting in the database. AsNoTracking can reduce change-tracking overhead for read-only results. If the returned entities will be updated directly, the tracking decision must be reconsidered.

6. Measuring the performance difference

Performance analysis is not limited to elapsed time. Also inspect returned row counts, memory usage, transferred columns and the database execution plan.

var stopwatch = Stopwatch.StartNew();

var correct = await context.Products
    .Where(p => p.IsActive && p.StockQuantity > 0)
    .OrderBy(p => p.Name)
    .Select(p => new ProductListItem
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .ToListAsync();

stopwatch.Stop();
Console.WriteLine($"Database filtering: {stopwatch.ElapsedMilliseconds} ms");

When comparing flawed and corrected versions, use the same database, connection conditions and similar cache conditions. Model creation and connection setup may distort the first measurement, so run each query several times and treat the first execution separately.

To inspect generated SQL before execution, use ToQueryString:

var query = context.Products
    .Where(p => p.IsActive)
    .OrderBy(p => p.Name)
    .Select(p => new { p.Id, p.Name });

Console.WriteLine(query.ToQueryString());
var data = await query.ToListAsync();

EF Core command logging can provide additional information. In production, be careful not to expose parameter values or other sensitive data in logs.

7. Common mistakes

  • Early ToList in a repository: If a repository materializes all entities before returning them, upper layers can no longer optimize the database query.
  • Expecting Include after ToList: An Include called after ToList is no longer EF Core's query-building operation because the data is already in memory.
  • Filtering inside a loop: Applying conditions in a foreach after loading all rows transfers unnecessary data.
  • Hiding the problem with AsQueryable: Calling AsQueryable on an in-memory list does not turn it back into a database query. Operations still execute as LINQ-to-Objects.
  • Ignoring translation limits: Custom C# methods cannot always be translated to SQL. Run the translatable part in the database first, then apply the client-side operation to a small result set.

8. Practice exercise

Write two versions that list orders created in the last 30 days with a total greater than 1,000.

  1. Create a flawed version that calls ToListAsync before applying the filters.
  2. Move Where, OrderByDescending, Select and Take before ToListAsync.
  3. Compare the generated SQL and returned row counts of both versions.
  4. Use a projection that returns only the order number, date and total.
  5. Measure time and memory behavior with both a small and a large dataset.

Conclusion

ToList is not inherently wrong. It is useful when the application intentionally needs a materialized collection. The problem occurs when it is called before database-translatable work has been completed. As a general rule, keep Where, Select, OrderBy, Take and similar operations before ToListAsync. Materialize the query only at the point where execution is actually required.

Understanding when a query changes from IQueryable to IEnumerable or to a concrete collection is essential for diagnosing EF Core performance problems. Regularly ask whether the query can be translated to SQL, how many rows are returned, which columns are transferred and which operations run in memory. These checks lead to faster and more maintainable data-access code.

Sources