Rule Definition
Calling .ToList() or .ToArray() materializes the query immediately, executing it and loading all results into memory. Applying additional LINQ operators after that (e.g., .Where(), .Select(), .OrderBy()) causes:
Unnecessary memory usage
Loss of deferred execution and query optimization
Performance bottlenecks with large datasets
Instead, you should:
Defer execution using .AsEnumerable() if you need to switch from LINQ to Entities to LINQ to Objects
Avoid materialization until absolutely necessary (e.g., at the end of the query chain)
Remediation
Apply further filtering/sorting operations before calling .ToList() or .ToArray().
Use .AsEnumerable() only when switching to in-memory LINQ processing is intentional.
Violation Code Sample
using System.Linq;
// ...
var data = dbContext.Users.ToList() // ⚠️ VIOLATION: query executes here
.Where(u => u.IsActive)
.OrderBy(u => u.Name);
// This loads all users into memory before filtering and sorting — a waste of resources if the dataset is large
Fixed Code Sample
using System.Linq;
// ...
// Execute filters in SQL before materializing
var data = dbContext.Users
.Where(u => u.IsActive)
.OrderBy(u => u.Name)
.ToList(); // ✓ FIXED: materialize after filtering/sorting
// If switching to LINQ-to-Objects explicitly
var data = dbContext.Users
.Where(u => u.IsActive)
.AsEnumerable() // ✓ FIXED : switch to in-memory for complex logic
.Where(u => SomeCustomFilter(u));
Reference
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/queryable-and-enumerable-operators
https://learn.microsoft.com/en-us/ef/core/performance/query-performance#avoid-premature-query-execution
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1862
Microsft Entity Framework - Efficient Querying - Buffering and streaming
https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying#buffering-and-streaming
LINQ Stinks - code smells in your LINQ - LINQ Stink #2 - Reading too much
https://www.markheath.net/post/linq-stinks
Enhancing Database Query Performance with Entity Framework Core: Real-world Examples and Performance Metrics
Example 3: Query Projection for Minimizing Data Transfer
https://mohamed-hendawy.medium.com/enhancing-database-query-performance-with-entity-framework-core-real-world-examples-and-3899f285e67c
Related Technologies
Technical Criterion
Efficiency - SQL and Data Handling Performance
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.