Coder Perfect

In LINQ, you can flatten a list.

Problem

I have a LINQ query that produces IEnumerableListint>>, but I just want to return Listint>, thus I’d like to merge all of my IEnumerableListint>> records into a single array.

Example :

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

I want to put all of my IEnumerableListint>> results into a single Listint>.

As a result, [1,2,3,4] and [5,6,7] are generated from source arrays.

Only one array [1,2,3,4,5,6,7] is required.

Thanks

Asked by C├ędric Boivin

Solution #1

Try SelectMany()

var result = iList.SelectMany( i => i );

Answered by Mike Two

Solution #2

With query syntax:

var values =
from inner in outer
from value in inner
select value;

Answered by recursive

Solution #3

iList.SelectMany(x => x).ToArray()

Answered by Dylan Beattie

Solution #4

You can do this if you have a ListListint>> k.

List<int> flatList= k.SelectMany( v => v).ToList();

Answered by Daniel

Solution #5

Like this?

var iList = Method().SelectMany(n => n);

Answered by mqp

Post is based on https://stackoverflow.com/questions/1590723/flatten-list-in-linq