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
| Family | Operators |
|---|---|
| Filter | Where, OfType |
| Project | Select, SelectMany |
| Sort | OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse, Order |
| Group | GroupBy, ToLookup, CountBy, AggregateBy |
| Join | Join, GroupJoin, LeftJoin/RightJoin (.NET 10), Zip |
| Set | Distinct(By), Union(By), Intersect(By), Except(By), Concat |
| Partition | Skip, Take, SkipWhile, TakeWhile, Chunk, TakeLast |
| Element | First, Single, Last, ElementAt (+OrDefault) |
| Quantifier | Any, All, Contains |
| Aggregate | Count, Sum, Min, Max, MinBy, MaxBy, Average, Aggregate |
| Convert | ToList, ToArray, ToDictionary, ToHashSet, ToLookup, AsEnumerable, AsQueryable, Cast |
| Generate | Range, 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).