Home > Backend Development > C++ > How Can LINQ's SelectMany() Method Flatten a Nested List of Integers?

How Can LINQ's SelectMany() Method Flatten a Nested List of Integers?

Patricia Arquette
Release: 2025-01-26 15:36:09
Original
366 people have browsed it

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>
Copy after login

The desired output is:

<code>[1, 2, 3, 4, 5, 6, 7]</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template