typestar

SelectMany in C#

Flatten a sequence of sequences into one stream.

var teams = new Dictionary<string, string[]>
{
    ["compilers"] = new[] { "Ada", "Grace" },
    ["theory"] = new[] { "Alan", "Kurt" },
};

// SelectMany flattens one level: all members, one sequence
var everyone = teams.SelectMany(t => t.Value);
Console.WriteLine(string.Join(",", everyone));

// keep the team name attached to each member
var pairs = teams.SelectMany(t => t.Value.Select(m => $"{m}@{t.Key}"));
Console.WriteLine(string.Join(" ", pairs));

How it works

  1. SelectMany(t => t.Value) yields every member of every team.
  2. The nested Select keeps the team name attached to each member.
  3. One level of nesting disappears per call.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
448
Tokens
102
Three-star pace
85 tpm

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

Type this snippet

Step 2 of 3 in Shaping, step 2 of 17 in LINQ in depth.

← Previous Next →