Tip #001
Flatten a collection of collections
About this tip
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 coffeeCode
int[][] numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
// classic LINQvar values = numbers.SelectMany(n => n).ToList();
// C# 12: collection expression + spreadList<int> modern = [.. numbers.SelectMany(n => n)];
Console.WriteLine(string.Join(", ", modern));Output
$ dotnet run flatten.cs1, 2, 3, 4, 5, 6, 7, 8, 9