Roadmap › 1. .NET › Step 14
LQ

LINQ — Language Integrated Query

Query vs method syntax, deferred execution, filtering, projection, ordering, grouping, joins, aggregation, set and element operators, IEnumerable vs IQueryable, expression trees, performance and the classic LINQ interview programs.
Quick revision for interview day. Print it or save it as a PDF.

Operator families

FamilyOperators
FilterWhere, OfType
ProjectSelect, SelectMany
SortOrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse, Order
GroupGroupBy, ToLookup, CountBy, AggregateBy
JoinJoin, GroupJoin, LeftJoin/RightJoin (.NET 10), Zip
SetDistinct(By), Union(By), Intersect(By), Except(By), Concat
PartitionSkip, Take, SkipWhile, TakeWhile, Chunk, TakeLast
ElementFirst, Single, Last, ElementAt (+OrDefault)
QuantifierAny, All, Contains
AggregateCount, Sum, Min, Max, MinBy, MaxBy, Average, Aggregate
ConvertToList, ToArray, ToDictionary, ToHashSet, ToLookup, AsEnumerable, AsQueryable, Cast
GenerateRange, Repeat, Empty

Deferred vs immediate

Deferred: returns IEnumerable/IQueryable. Immediate: returns a value, collection or element.

IEnumerable vs IQueryable

Delegates, in memory vs expression trees, translated to SQL. Keep IQueryable until ToListAsync().

Classic snippets

csharp
list.OrderByDescending(x => x.Salary).Skip(1).First();          // 2nd highest
list.GroupBy(x => x.Dept).Select(g => new { g.Key, C = g.Count() });
list.GroupBy(x => x.Email).Where(g => g.Count() > 1);            // duplicates
from c in cs join o in os on c.Id equals o.CId into g from o in g.DefaultIfEmpty() select ...;  // left join
words.GroupBy(w => w).ToDictionary(g => g.Key, g => g.Count());  // word frequency
string.Join(",", list.Select(x => x.Name));
nested.SelectMany(x => x.Items);

Pitfalls

ToList() too early · multiple enumeration · Count() > 0 instead of Any() · First without OrderBy · N+1 with lazy loading · untranslatable methods in IQueryable · list.Contains in loops (use HashSet).