Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

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 Tips to Avoid Common Pitfalls

- 26.05.26 - ErcanOPAK

⚡ LINQ is Beautiful, But Know Its Cost

LINQ makes code readable, but hidden performance traps exist. Multiple enumerations, wrong collection types, predicate order — fix them all.

❌ Multiple Enumeration

var filtered = items.Where(x => x.IsActive);
// Executes query 3 times!
var count = filtered.Count();      // Query executes
var first = filtered.First();       // Query executes again
var list = filtered.ToList();      // And again!

// Database: 3 round trips!

✅ Materialize Once

// Materialize to list
var filtered = items.Where(x => x.IsActive).ToList();

// Now uses the list, no re-query
var count = filtered.Count;     // O(1)
var first = filtered.First();    // O(1)
var list = filtered;             // Already list

📊 Performance Comparison

// ❌ Slow: Where after OrderBy
var result = items.OrderBy(x => x.Name).Where(x => x.IsActive);
// Orders ALL items, then filters

// ✅ Fast: Where before OrderBy
var result = items.Where(x => x.IsActive).OrderBy(x => x.Name);
// Filters first (fewer items), then orders

// ❌ Slow: First() without Any()
if (items.Where(x => x.IsActive).FirstOrDefault() != null) { }
// Scans entire collection

// ✅ Fast: Any() first
if (items.Any(x => x.IsActive))
{
    var item = items.First(x => x.IsActive);
}

// ✅ Best: Use FirstOrDefault
var item = items.FirstOrDefault(x => x.IsActive);
if (item != null) { }

✅ Collection Type Matters

  • List.Count: O(1) → Fast
  • IEnumerable.Count(): O(n) → Slow (enumerates)
  • HashSet.Contains: O(1) → Fast for lookups
  • List.Contains: O(n) → Slow for large collections
  • Dictionary lookup: O(1) → Fast by key

📝 Real-World Example

// ❌ Bad: 3 enumerations + OrderBy before filter
var activeUsers = users.Where(u => u.IsActive);
var total = activeUsers.Count();           // Enumerates 1
var list = activeUsers.ToList();           // Enumerates 2
var first = activeUsers.First();            // Enumerates 3
var sorted = users.OrderBy(u => u.Name)    // Orders all (1000 items)
    .Where(u => u.IsActive);               // Then filters (maybe 100)

// ✅ Good: Single enumeration + filter first
var activeUsers = users.Where(u => u.IsActive).ToList();  // 1 enumeration
var total = activeUsers.Count;               // O(1)
var list = activeUsers;                      // Already list
var first = activeUsers[0];                  // O(1)

var sorted = users.Where(u => u.IsActive)   // Filters first (100)
    .OrderBy(u => u.Name)                    // Orders only 100
    .ToList();

💡 LINQ to SQL/EF Core Tips

  • Use .Any() instead of .Count() > 0: Translates to EXISTS
  • Avoid .ToList() too early: Let database filter, then materialize
  • Use .Select() projections: Only get needed columns
  • Use .Include() for navigation properties: Avoid N+1 queries
  • Monitor generated SQL: Use logging to see what’s executed

“Method was called 10,000 times. Each call enumerated a collection 3 times. Total: 30,000 iterations. Fixed by materializing once. Method went from 500ms to 15ms. LINQ is great, but know what it’s doing.”

— Performance Engineer

Related posts:

C#: Use Task-Based Asynchronous Pattern (TAP)

C#: Use Task-Based Asynchronous Pattern (TAP)

C#: Fix a Deconstruct Method Never Matching a Pattern Switch

C#: Fix a Deconstruct Method Never Matching a Pattern Switch

C#: Async/Await Best Practices for High-Performance Apps

C#: Async/Await Best Practices for High-Performance Apps

Views: 25

Post navigation

C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues
Visual Studio: Use IntelliCode for AI-Powered Code Completion

Leave a Reply Cancel reply

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

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

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

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

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