Home > Backend Development > C++ > How to Flatten an `IEnumerable` into a `List` using LINQ?

How to Flatten an `IEnumerable` into a `List` using LINQ?

Linda Hamilton
Release: 2025-01-26 15:46:09
Original
706 people have browsed it

How to Flatten an `IEnumerable` into a `List` using LINQ?

Streamlining Nested LINQ Queries: Flattening IEnumerable<List<int>> to List<int>

Working with nested collections in LINQ often requires flattening them into a single list for easier processing. The SelectMany() method provides an elegant solution for this common task.

Scenario:

Your LINQ query returns an IEnumerable<List<int>>—a collection of integer lists. The goal is to transform this into a single List<int>.

Solution:

The SelectMany() method efficiently flattens the nested structure. Here's how:

<code class="language-csharp">var result = iList.SelectMany(i => i).ToList();</code>
Copy after login

The SelectMany() method iterates through each inner list (i) within iList and projects its elements into a single sequence. The .ToList() extension method then converts this sequence into a List<int>.

Illustration:

Let's say your input is:

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

Applying SelectMany() yields:

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

This approach simplifies nested data structures, making your LINQ queries more concise and readable. It's a valuable technique for handling various scenarios involving hierarchical data.

The above is the detailed content of How to Flatten an `IEnumerable` into a `List` using LINQ?. 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