LINQ in Depth

19.1 Query Syntax Clauses (VB)

From c In customers Where c.Country = "IN" Select c.Name, c.City Order By... [Descending] Order By c.Name, c.Age Descending Let total = o.Qty * o.Price Join... On... Equals Group Join... Into grouped / left join Group By... Into

Group By c.City Into Count(), Avg = Average(c.Age), Group Aggregate... Into

Aggregate o In orders Into Sum(o.Total) (VB only) Select c.City Distinct

Skip, Take, Skip While, Take While Paging and partitioning

Dim report = From o In orders
             Join c In customers On o.CustomerId Equals c.Id
             Where o.Date.Year = 2025
             Group By c.Country Into Orders = Count(), Revenue = Sum(o.Total)
             Order By Revenue Descending
             Select Country, Orders, Revenue

Dim stats = Aggregate o In orders Into Count(), Total = Sum(o.Total), Avg = Average(o.Total), Max(o.Total)

19.2 Method Syntax and Operators

Where, OfType, Distinct, DistinctBy (.NET 6) Select, SelectMany, Zip, Chunk

OrderBy, ThenBy, OrderByDescending, Reverse, Order (.NET 7)

GroupBy, Join, GroupJoin, ToLookup Union, Intersect, Except, UnionBy, ExceptBy Any, All, Contains

First(OrDefault), Single(OrDefault), Last, ElementAt

Count, Sum, Min, Max, MinBy, MaxBy, Average, Aggregate Enumerable.Range, Repeat, Empty

ToList, ToArray, ToDictionary, ToHashSet, AsEnumerable, Cast

Dim topCustomers = orders.GroupBy(Function(o) o.CustomerId).
                          Select(Function(g) New With {.Id = g.Key, .Total = g.Sum(Function(o) o.Total)}).
                          OrderByDescending(Function(x) x.Total).
                          Take(5).
                          ToList()
Dim byCity = customers.ToLookup(Function(c) c.City)
Dim puneCustomers = byCity("Pune")

19.3 Deferred Execution and IQueryable

IEnumerable(Of T) LINQ runs in memory (delegates). IQueryable(Of T) (EF Core) builds expression trees that are translated to SQL. Watch for client-side evaluation and N+1 queries.

Execution happens on enumeration. Materialize once (ToList) when you reuse results.

PLINQ: .AsParallel().WithDegreeOfParallelism(4) (Module 29).