Step 1 of 4 · Reading · ~2 min
Learn
LINQ and Exceptions
LINQ in VB.Net has a more SQL-like surface than C#'s. Both syntaxes work —
on a current compiler. Read this lesson as reference, not as something to
run here: the grader's vbnc predates lambdas and query expressions, so
every fenced block below is illustration only, and the exercise at the end
asks for the explicit loop that LINQ is sugar over.
Method syntax — same shape as C#:
Dim nums As Integer() = {1, 2, 3, 4, 5}
Dim sumOfSquares = nums.Where(Function(n) n Mod 2 = 0) _
.Select(Function(n) n * n) _
.Sum()
' 4 + 16 = 20
Query syntax — VB style:
Dim result = From n In nums
Where n Mod 2 = 0
Select n * n
Dim total = result.Sum() ' 20
The two compile to the same thing. Query syntax reads better when there are
joins, groupings or several Order By keys; method syntax reads better for
one or two operators.
Deferred execution is the trap. From n In nums Where ... does no work
at all. It builds a query object that remembers what to do. The loop runs
when something enumerates it — .Sum(), .ToList(), a For Each. Mutate
nums between the query and the enumeration and you get the new data.
Enumerate the same query twice and the work happens twice.
VB has clauses C#'s query syntax lacks:
Dim total = Aggregate n In nums Into Sum(n)
Dim sorted = From p In people
Order By p.Age Descending
Select p.Name
Dim oldest3 = (From p In people
Order By p.Age Descending
Select p.Name).Take(3).ToList()
Aggregate ... Into Sum(n) returns the single total, not a sequence — it is
one of the few clauses that forces execution immediately.
Group By:
Dim grouped = From p In people
Group By p.Department Into Group
Select Department, Count = Group.Count()
The extension methods behind all of it, usable without query syntax:
Where, Select, OrderBy, OrderByDescending, GroupBy, Distinct,
Take, Skip, Sum, Average, Max, Min, Count, First,
FirstOrDefault, Single, Any, All, ToList, ToArray,
ToDictionary, ToLookup.
Writing the same thing by hand
Every LINQ chain is a loop with a filter, a projection and an accumulator. This is what the exercise asks for, and it is what the compiler emits:
Dim total As Long = 0
For Each n As Integer In nums
If n Mod 2 = 0 Then
total = total + CLng(n) * n
End If
Next
' total = 20 — the same answer the chain above produces
Knowing this loop is why LINQ is readable rather than magic.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…