LINQ in Practice · Lesson 8

Flattening nested data

Turn several child sequences into one stream.

How it works

SelectMany projects each parent to a child sequence and combines the requested children into one flattened sequence. The teams contain different numbers of members, but the final result is a single ordered stream of names. Select alone would produce a sequence of arrays instead. Flattening loses the parent relationship unless the projection carries it forward. For a report that needs both team and member, use the result-selector overload or project a tuple containing both.

Keep in mind that duplicate child values remain duplicates: flattening describes traversal, not deduplication or a claim that names identify unique people.

Add an empty team and a repeated name. Predict the flattened output, then design a projection that retains an explicit team identifier beside each member.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var teams = new[] { new[] { "Ada", "Lin" }, new[] { "Sam" } };
Console.WriteLine(string.Join(",", teams.SelectMany(team => team)));

Expected output

Ada,Lin,Sam
Try this
SelectMany flattens one level; it does not remove duplicates.