Home >Backend Development >C++ >How Can I Flatten a Nested IEnumerable in LINQ?

How Can I Flatten a Nested IEnumerable in LINQ?

Susan Sarandon
Susan SarandonOriginal
2025-01-26 15:51:09941browse

How Can I Flatten a Nested IEnumerable in LINQ?

Using LINQ to flatten nested IEnumerable

In LINQ, you may encounter nested IEnumerables that need to be "flattened" to obtain a single merged IEnumerable. This flattening process becomes necessary when the inner IEnumerable contains elements of the same type as the outer IEnumerable.

Case Study:

Consider the examples provided:

<code>IEnumerable<List<int>> iList = from number in
    (from no in Method() select no) select number;</code>

In this example, iList represents a nested IEnumerable, where each element is itself a List. The goal is to merge all these nested lists into a single List.

Solution: SelectMany()

LINQ provides the SelectMany() method, which is specifically used to flatten nested IEnumerable collections. It iterates over the outer IEnumerable and projects each inner collection element into a new IEnumerable.

To get the desired result you can use SelectMany() as follows:

<code>var result = iList.SelectMany(i => i);</code>

In this code, the SelectMany() method takes each list contained in iList (represented by the variable i) and concatenates the elements of that list into a new flattened IEnumerable named result.

Example:

With this flattening, the original nested arrays [1,2,3,4] and [5,6,7] will be combined into a single array [1,2,3,4,5,6,7] as expected ].

The above is the detailed content of How Can I Flatten a Nested IEnumerable in LINQ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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