Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: LINQ Performance Optimization Techniques

- 15.08.26 - ErcanOPAK

⚡ LINQ Performance = Fast Queries

LINQ can be slow. Performance optimization makes LINQ queries fast and efficient.

📝 Optimization Techniques

// 1. Use Any() instead of Count() > 0
bool hasItems = data.Any();  // Good
bool hasItems = data.Count() > 0;  // Bad

// 2. Filter Before Projection
var result = data
    .Where(x => x.IsActive)  // Filter first
    .Select(x => x.Name)      // Then project
    .ToList();

// 3. Use SelectMany instead of Nested Loops
var allItems = data.SelectMany(x => x.Items).ToList();

// 4. Use ToLookup for Grouped Access
var lookup = data.ToLookup(x => x.Category);
var electronics = lookup["Electronics"];

// 5. Use HashSet for Existence Checks
var ids = new HashSet(data.Select(x => x.Id));
bool exists = ids.Contains(id);  // O(1)

// 6. Use Parallel LINQ for Large Datasets
var result = data
    .AsParallel()
    .WithDegreeOfParallelism(Environment.ProcessorCount)
    .Where(x => x.IsActive)
    .Select(x => ProcessItem(x))
    .ToList();

🎯 Advanced Optimization

// 7. Avoid Multiple Enumerations
var data = GetData();
var count = data.Count();  // First enumeration
var first = data.First();  // Second enumeration - Bad!

// Good: Materialize once
var data = GetData().ToList();
var count = data.Count();
var first = data.First();

// 8. Use Compiled Queries (EF Core)
private static readonly Func> GetUserById =
    EF.CompileAsyncQuery((MyContext ctx, int id) =>
        ctx.Users.FirstOrDefault(u => u.Id == id));

// 9. Use Select for Projection
var names = users.Select(u => u.Name);  // Only names
var fullUsers = users.ToList();  // All data - Bad!

// 10. Use Index for Performance
var data = new List { 1, 2, 3, 4, 5 };
var result = data
    .Select((item, index) => new { item, index })
    .Where(x => x.item % 2 == 0)
    .Select(x => $"Item {x.index}: {x.item}")
    .ToList();

// 11. Use Chunk for Batch Processing
var chunks = data.Chunk(100);  // .NET 6+
foreach (var chunk in chunks)
{
    ProcessChunk(chunk);
}

// 12. Use Take/Skip for Pagination
var page = data
    .Skip(pageNumber * pageSize)
    .Take(pageSize)
    .ToList();

💡 LINQ Optimization Tips

  • Filter before projection
  • Use Any() instead of Count()
  • Avoid multiple enumerations
  • Use ToLookup for grouping
  • Use Parallel LINQ for large data

Optimized LINQ queries are essential for performance. They make your application faster and more scalable.

— Performance Architect

Related posts:

What is the difference between 'ref' and 'out' keywords in C#

Why BackgroundService Beats Task.Run in APIs

C#: Use Record Types with With-Expressions for Immutable Data Transformations

Post Views: 8

Post navigation

C#: Async/Await Best Practices for Web APIs
Visual Studio: Refactoring Tools for Clean Code

Leave a Reply Cancel reply

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

October 2026
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Sep    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (952)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (837)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (624)
  • Add Constraint to SQL Table to ensure email contains @ (590)
  • Average of all values in a column that are not zero in SQL (553)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (526)
  • Find numbers with more than two decimal places in SQL (468)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps
  • Photoshop: Fix a Color Profile Mismatch That Makes Printed Output Look Nothing Like What You Saw On Screen
  • WordPress: Fix Search Results That Return Pages From a Theme You Deactivated Months Ago
  • Visual Studio: Fix a Test Project That Builds Fine Alone but Fails to Discover Any Tests After a NuGet Restore
  • ASP.NET Core: Fix a File Upload That Times Out on Slow Connections Only Because Kestrel’s Minimum Data Rate Feature Kicked In
  • JavaScript: Fix an Array Destructuring Default Value That Silently Never Applies Because null Was Passed Instead of Undefined

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (952)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (837)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com