Home >Backend Development >C++ >How Can LINQ's SelectMany() Method Flatten a Nested List of Integers?
Using LINQ's SelectMany() to Flatten Nested Integer Lists
LINQ queries often produce nested collections, like IEnumerable<List<int>>
. The SelectMany()
method efficiently flattens these into a single list.
The Challenge:
Suppose a LINQ query returns a list of lists of integers (IEnumerable<List<int>>
). The task is to combine these inner lists into a single, one-dimensional List<int>
.
Illustrative Example:
Starting with these input lists:
<code>[1, 2, 3, 4] and [5, 6, 7]</code>
The desired output is:
<code>[1, 2, 3, 4, 5, 6, 7]</code>
Solution with SelectMany():
LINQ's SelectMany()
simplifies this process. Here's how to flatten the nested list:
<code class="language-csharp">var nestedList = new List<List<int>> { new List<int> { 1, 2, 3, 4 }, new List<int> { 5, 6, 7 } }; var flattenedList = nestedList.SelectMany(innerList => innerList).ToList(); </code>
Explanation:
nestedList
: This represents the input list of lists.SelectMany(innerList => innerList)
: This is the core of the solution. SelectMany()
iterates through each innerList
in nestedList
. The lambda expression innerList => innerList
simply projects each inner list onto itself, effectively unwrapping the nesting..ToList()
: This converts the resulting flattened sequence into a List<int>
.This concise code efficiently flattens the nested list, providing the desired single-dimensional list of integers.
The above is the detailed content of How Can LINQ's SelectMany() Method Flatten a Nested List of Integers?. For more information, please follow other related articles on the PHP Chinese website!