typestar

group ... into in C#

Group inside a query and keep querying over the groups.

var commits = new[]
{
    (Author: "ada", Files: 3), (Author: "alan", Files: 1),
    (Author: "ada", Files: 5), (Author: "kurt", Files: 2),
};

// group ... by ... into g continues the query over the groups
var summary =
    from c in commits
    group c by c.Author into g
    orderby g.Sum(c => c.Files) descending
    select $"{g.Key}: {g.Count()} commits, {g.Sum(c => c.Files)} files";

Console.WriteLine(string.Join("\n", summary));

How it works

  1. group c by c.Author into g restarts the query per group.
  2. g.Key, g.Count() and g.Sum(...) summarize each author.
  3. orderby ranks the groups, not the rows.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
413
Tokens
94
Three-star pace
85 tpm

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

Type this snippet

Step 3 of 3 in Query syntax, step 12 of 17 in LINQ in depth.

← Previous Next →