October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

LINQ Performance: How to Make C# Queries Faster

LINQ performance depends on where a query runs. Learn how to diagnose EF Core database costs, avoid repeated in-memory work, and optimize with measurements.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To make a LINQ query faster, first find where its work happens. LINQ to Objects runs operators in your application; EF Core can translate a query to SQL, where the database plan, indexes, rows transferred, and roundtrips often matter more than small syntax changes. Measure the slow path, then optimize that specific cost.

First identify which LINQ execution context you have

A query over an in-memory collection and an EF Core query may look similar in C#, but they do different work. LINQ to Objects executes .NET operators against objects. EF Core builds a query representation, translates supported parts into database-specific commands, and relies on the database to execute them. The distinction affects where filtering, sorting, and projection happen—and what to inspect when performance is poor. See Microsoft’s explanation of how EF Core queries work.

As an Amazon Associate I earn from qualifying purchases.

  • LINQ to Objects: investigate enumeration count, allocations, operator behavior, and collection size.
  • EF Core: inspect generated SQL, database execution plan, index use, transferred data, roundtrips, and EF-side overhead.

For EF Core, diagnose the database work first

Before rewriting a fluent expression, inspect the SQL it produces and the database’s execution plan. A query can be slow because it scans a large table, fetches columns the application does not need, returns too many rows, or makes too many trips to the database. Microsoft’s EF Core efficient-querying guidance recommends focusing on the work performed by the database and the data sent back.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Project only the properties you need

Returning complete entities when a screen or calculation needs only a few fields transfers extra data. Project the required values into a result shape:

var rows = await db.Orders
    .Where(order => order.Status == OrderStatus.Open)
    .Select(order => new { order.Id, order.CreatedAt })
    .ToListAsync();

Keep the filter and projection in the provider-translated query so the database can limit the rows and columns it returns. Verify the SQL rather than assuming a particular expression translates as intended.

Constrain result sizes with intent

Use filters and pagination when a consumer does not need the entire result set. Pagination helps control large result sizes, but it is not a universal speed switch: separate page requests add roundtrips, and performance still depends on the query plan and workload. Avoid loading an unbounded result merely because the query is concise.

Check indexes and the execution plan

If a filter or sort is unexpectedly expensive, check whether the plan uses suitable indexes or scans more data than expected. LINQ syntax alone cannot ensure an index is used; generated SQL, database schema, and optimizer decisions determine that. An index also has costs, so base schema changes on the workload and database evidence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reduce relationship-loading surprises and database trips

Lazy loading can create an N+1 pattern: the initial query loads a set of entities, then accessing a related collection for each entity triggers another query. The result may be many roundtrips even though the code appears to make one request. Make relationship loading deliberate with projection, eager loading, or explicit loading according to what the operation needs.

Loading several related collections in one query can produce a large joined result with repeated data, sometimes called cartesian explosion. EF Core split queries can help in some cases, but they use additional database roundtrips. Compare the total transferred data and trip count for the actual query rather than treating either single-query or split-query loading as always superior. Microsoft discusses these tradeoffs in its efficient querying guidance.

Keep database work on the server until you mean to cross over

EF Core translates supported expression-tree operations into database language. Calling AsEnumerable or AsAsyncEnumerable changes subsequent operators to run locally; it does not make the database perform those operations. If a filter is applied only after that boundary, the database may send many rows that the application then discards.

var localResults = db.Products
    .Where(product => product.IsAvailable) // provider-translated filter
    .AsEnumerable()
    .Where(product => CustomRule(product)); // runs in application memory

Use a client-side boundary only when a required operation cannot be translated or local processing is intentional, and constrain the server-side result first where possible. EF Core’s client-versus-server evaluation documentation explains where evaluation occurs and the consequences of client-side work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use tracking only when the operation needs it

For read-only results that will not be updated through the context, a no-tracking query can avoid change-tracking work. Tracking is useful when entities need to be modified and saved; identity resolution and relationship behavior can also affect which mode is appropriate. Choose based on how the results will be used, not on a blanket assumption that no-tracking is always better.

Understand when LINQ to Objects evaluates and buffers

Many sequence-returning LINQ operators defer their work until the sequence is enumerated. A query declaration therefore does not necessarily mean the work has happened. Scalar operations such as Count and First execute to produce a result; ToList and ToArray enumerate and materialize results. Microsoft’s LINQ to Objects overview describes these execution patterns.

Enumerating a deferred query repeatedly can repeat its work and may observe changes to the source between enumerations. Materialization is useful when you need to reuse a stable snapshot, but avoid creating a list just to add another sequence operation if you will enumerate only once.

Deferred execution does not mean every operator streams one item at a time. For example, OrderBy must consume and sort its input before it can yield the first ordered result. Microsoft’s deferred-execution and lazy-evaluation guidance covers this distinction.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose buffering or streaming based on how results are consumed

ToList and ToArray buffer results in application memory, which is practical when the complete result is needed or reused. Async enumeration can stream results to a consumer without first building a full application-side list. Streaming does not guarantee zero buffering throughout the stack: EF Core can buffer internally in particular circumstances, including retrying execution strategies and some split-query cases. Account for result size, memory, failure behavior, and consumer needs.

Consider EF Core micro-optimizations only after profiling

EF Core caches query shapes, and parameterizing runtime values can allow reuse of query compilation and database plans. Explicit compiled queries may reduce EF-side overhead on hot paths, but the gain depends on the workload and platform. They do not fix a poor database plan or excessive data transfer.

Context pooling is another advanced option when profiling shows context setup overhead matters. These changes are workload-sensitive; Microsoft’s advanced performance guidance says to “benchmark on your platform before making any decisions.” Its documented benchmark examples are not universal performance guarantees.

A practical order for troubleshooting a slow query

  1. Classify the query: determine whether it is LINQ to Objects or provider-backed EF Core.
  2. Measure the slow operation: use representative data and capture latency and, where relevant, allocations.
  3. For EF Core, inspect SQL and the plan: look for scans, unnecessary columns, unbounded results, and extra roundtrips.
  4. Check evaluation boundaries and loading: identify client-side work, repeated enumeration, lazy-loading N+1 behavior, and collection joins.
  5. Change one cost at a time: compare results and performance under the same representative conditions.
  6. Only then test advanced options: consider compiled queries or context pooling when measurements point to EF-side overhead.

If a provider cannot generate the database-specific operation you need, raw SQL, database functions, or views are possible alternatives. Raw SQL adds maintenance cost, so Microsoft frames it as a last resort rather than a default optimization.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.