Optimizing Performance using Efficient LINQ queries

Combining Where and FirstOrDefault()

Problem: Using Where and then FirstOrDefault results in redundant filtering.

//BAD code
var user = collection.Where(x => x.Id == id).FirstOrDefault();


// Efficient Code
var user = collection.FirstOrDefault(x => x.Id == id);


Efficient Contains Usage

Problem: Checking for existence in lists can be slow.

// Bad code
var result = collection.Where(x => list.Contains(x.Id)).ToList();

// Efficient code
var set = new HashSet<int>(list);
var result = collection.Where(x => set.Contains(x.Id)).ToList();


Efficient Distinct Usage

Problem: Using Distinct on large datasets can be slow.

var result = collection.Select(x => x.Name).Distinct().ToList();


//Efficient code
var result = collection.Select(x => x.Name).ToHashSet();


Using LongCount for Large Collections

Problem: Count on very large collections can overflow.

var count = collection.LongCount();