Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 42 / 68

Flattening an Array

In this lesson you will learn how to flatten a nested array with SelectMany in C#, so a complex structure becomes simple to work with. This is for anyone searching for "C# SelectMany flatten how to use".

Expanding an array that contains other arrays into one flat array is called flattening. LINQ's .SelectMany() does it in one line.

The sample code runs nested.SelectMany(x => x).ToArray() on the nested int[][] nested and expands it into the single array {1, 2, 3, 4, 5}. The simple lambda x => x is what expands each inner array as-is.

A common stumbling block for beginners is the difference from .Select(). With .Select() alone the arrays remain nested; .SelectMany() is what removes one level.

In real-world development, SelectMany is one of the most powerful LINQ methods, and the same thinking applies when you want to collapse multi-level tree data into a single list.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)