Smooth gear array in C #

Is there an elegant way to smooth a 2D array in C # (using Linq or not)?

eg. suppose

var my2dArray = new int[][] { new int[] {1,2,3}, new int[] {4,5,6} }; 

I want to call something like

 my2dArray.flatten() 

what will give

 {1,2,3,4,5,6} 

Any ideas?

+6
source share
1 answer

You can use SelectMany

 var flat = my2dArray.SelectMany(a => a).ToArray(); 

This will work with a gear array, as in your example, but not with a 2D array, for example

 var my2dArray = new [,] { { 1, 2, 3 }, { 1, 2, 3 } }; 

But in this case, you can iterate over values ​​like this

 foreach(var item in my2dArray) Console.WriteLine(item); 
+22
source

All Articles