Advanced LINQ combines grouping, joins, and aggregation—expressing data transforms declaratively instead of nested loops. Understanding IEnumerable<T> and deferred execution prevents subtle bugs in production pipelines.
GroupBy and aggregation
var words = new[] { "cat", "car", "bat" };
var byLetter = words.GroupBy(w => w[0]);
foreach (var g in byLetter) {
Console.WriteLine($"{g.Key}: {g.Count()}");
}
First, Single, Any
nums.First(n => n > 10); // throws if none
nums.FirstOrDefault(n => n > 10);
nums.Any(n => n < 0);
Choose FirstOrDefault when absence is valid—First throws InvalidOperationException.
Important interview questions and answers
- Q: IEnumerable vs IQueryable?
A:IEnumerableruns in memory;IQueryablecan be translated to remote providers (SQL)—don't mix blindly. - Q: Materialize when?
A: CallToListorToArraywhen you need stable snapshots or multiple passes.
Self-check
- What does GroupBy return?
- First vs FirstOrDefault?
Pitfall: IQueryable builds expression trees for providers like EF—do not mix arbitrary in-memory logic that cannot translate to SQL.
Interview prep
- IEnumerable vs IQueryable?
IEnumerableruns in memory;IQueryablebuilds expression trees for providers like EF Core to translate to SQL.- GroupBy use case?
Partition elements by a key—returns groups for aggregation or reporting, similar to SQL GROUP BY.