typestar

Group By and Aggregate in Visual Basic

Bucketing values and folding a whole sequence in one query.

Dim words = {"fig", "plum", "kiwi", "date", "yuzu", "sloe", "pear"}

Dim byLength = From w In words
               Group By size = w.Length Into bunch = Group
               Order By size

For Each g In byLength
    Console.WriteLine($"{g.size}: {String.Join(", ", g.bunch)}")
Next

Dim stats = Aggregate w In words
            Into total = Count(), longest = Max(w.Length)
Console.WriteLine($"{stats.total} words, longest runs {stats.longest}")

How it works

  1. Group By size = ... Into bunch = Group names the key and the bucket.
  2. Each result row carries size and its bunch of members.
  3. Aggregate ... Into Count(), Max(...) computes several folds at once.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
399
Tokens
101
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 3 of 3 in LINQ, step 12 of 29 in Language basics.

← Previous Next →