CodexBloom - Programming Q&A Platform

Inefficient LINQ Query Performance with Large Data Set in C#

👀 Views: 45 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-02
linq c# performance sql-server C#

I'm prototyping a solution and I'm currently working on a C# application that interacts with a large dataset (around 1 million records) using LINQ to SQL. I am experiencing important performance optimization with my LINQ query when filtering and sorting records. The following code snippet illustrates my current approach: ```csharp var filteredResults = dbContext.Records .Where(record => record.Status == "Active") .OrderBy(record => record.CreatedDate) .ToList(); ``` While this query works correctly, it's taking an unacceptably long time to execute, sometimes close to a minute. I have tried adding indexes to the `Status` and `CreatedDate` columns in SQL Server, but the performance is still lacking. I also considered using `AsNoTracking()` since I don't need to update these records, and I thought it could improve performance, but it didn't yield any noticeable results: ```csharp var filteredResults = dbContext.Records .AsNoTracking() .Where(record => record.Status == "Active") .OrderBy(record => record.CreatedDate) .ToList(); ``` I've checked the SQL generated by LINQ using SQL Server Profiler, and it seems to be well-formed, but the execution plan shows a lot of table scans instead of index seeks. I'm unsure how to optimize my LINQ query or if I should consider a different approach for handling such a large dataset. Any suggestions or best practices would be greatly appreciated! This is part of a larger REST API I'm building.