Flatten List in Linq

Flatten List in Linq

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

5 Answers

Try SelectMany()

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

With query syntax:

var values =
from inner in outer
from value in inner
select value;
4
iList.SelectMany(x => x).ToArray()
4

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

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

Like this?

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.