typestar

OrderBy & GroupBy in C#

Sorting with tie-breaks and grouping by computed keys.

var words = new[] { "fig", "apple", "cherry", "date", "banana" };

var byLength = words.OrderBy(w => w.Length).ThenBy(w => w);
Console.WriteLine(string.Join(",", byLength));

foreach (var group in words.GroupBy(w => w.Length))
{
    Console.WriteLine($"{group.Key}: {string.Join(",", group)}");
}

How it works

  1. OrderBy(...).ThenBy(...) sorts by length, then alphabetically.
  2. GroupBy yields one group per key, each iterable on its own.
  3. group.Key is the value the group was formed around.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
292
Tokens
80
Three-star pace
90 tpm

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

Type this snippet

Step 2 of 3 in LINQ, step 23 of 29 in Language basics.

← Previous Next →