Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten List in LINQ

Tags:

c#

list

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

like image 946
Cédric Boivin Avatar asked Oct 19 '09 19:10

Cédric Boivin


People also ask

What is difference between select and SelectMany in LINQ?

Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.

How do you use SelectMany?

SelectMany(<selector>) method For example, SelectMany() can turn a two-dimensional array into a single sequence of values, as shown in this example: int[][] arrays = { new[] {1, 2, 3}, new[] {4}, new[] {5, 6, 7, 8}, new[] {12, 14} }; // Will return { 1, 2, 3, 4, 5, 6, 7, 8, 12, 14 } IEnumerable<int> result = arrays.


1 Answers

Try SelectMany()

var result = iList.SelectMany( i => i ); 
like image 196
Mike Two Avatar answered Sep 23 '22 06:09

Mike Two