Flatten List in LINQ

C#LinqList

C# Problem Overview


I have a LINQ query which returns IEnumerable<List<int>> but i want to return only List<int> so i want to merge all my record in my IEnumerable<List<int>> to only one array.

Example :

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

I want to take all my result IEnumerable<List<int>> to only one List<int>

Hence, from source arrays: [1,2,3,4] and [5,6,7]

I want only one array [1,2,3,4,5,6,7]

Thanks

C# Solutions


Solution 1 - C#

Try SelectMany()

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

Solution 2 - C#

With query syntax:

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

Solution 3 - C#

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

Solution 4 - C#

If you have a List<List<int>> k you can do

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

Solution 5 - C#

Like this?

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionC&#233;dric BoivinView Question on Stackoverflow
Solution 1 - C#Mike TwoView Answer on Stackoverflow
Solution 2 - C#recursiveView Answer on Stackoverflow
Solution 3 - C#Dylan BeattieView Answer on Stackoverflow
Solution 4 - C#DanielView Answer on Stackoverflow
Solution 5 - C#mqpView Answer on Stackoverflow