skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Flatten a collection of collections

C# 12

Code card showing SelectMany flattening three arrays; a C# 12 spread places the values in a list. Output: 1 through 9.

SelectMany flattens nested sequences into one. Spread puts the result into a list. It is available since C# 12. The key line is List<int> modern = [.. numbers.SelectMany(n => n)] in flatten.cs. Run it and the output reads 1, 2, 3, 4, 5, 6, 7, 8, 9.

Did this tip save you some time? Consider buying me a coffee to fuel the next one.

Buy me a coffee
flatten.cs
int[][] numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
// classic LINQ
var values = numbers.SelectMany(n => n).ToList();
// C# 12: collection expression + spread
List<int> modern = [.. numbers.SelectMany(n => n)];
Console.WriteLine(string.Join(", ", modern));
Output
$ dotnet run flatten.cs
1, 2, 3, 4, 5, 6, 7, 8, 9