Skip to content
LINQ in VB.Net
step 1/4

Reading — step 1 of 4

Learn

~1 min readLINQ and Exceptions

LINQ in VB.Net has a more SQL-like surface than C#'s. Both syntaxes work.

Method syntax — same as C#:

Dim nums = {1, 2, 3, 4, 5}
Dim sumOfSquares = nums.Where(Function(n) n Mod 2 = 0).Select(Function(n) n * n).Sum()
' 20

Query syntax — VB style:

Dim result = From n In nums
             Where n Mod 2 = 0
             Select n * n

Dim total = result.Sum()

VB has additional clauses C#'s LINQ syntax doesn't:

  • Aggregate — like Sum but for any aggregate
  • Distinct, Skip, Take as direct keywords
  • Order By ... Descending
Dim summary = Aggregate n In nums Into Sum(n)
' just the sum, in one line

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()

Group By:

Dim grouped = From p In people
              Group By p.Department Into Group
              Select Department, Count = Group.Count()

Common LINQ extension methods (all available):

  • .Where(...), .Select(...), .OrderBy(...), .OrderByDescending(...)
  • .Sum, .Average, .Max, .Min, .Count
  • .GroupBy(...)
  • .Distinct, .Take(n), .Skip(n)
  • .First, .FirstOrDefault, .Single, .Any, .All
  • .ToList, .ToArray, .ToDictionary, .ToLookup

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…