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
OrderBy(...).ThenBy(...)sorts by length, then alphabetically.GroupByyields one group per key, each iterable on its own.group.Keyis the value the group was formed around.
Keywords and builtins used here
foreachgroupinnewstringvar
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.
Step 2 of 3 in LINQ, step 23 of 29 in Language basics.