Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten jagged array in C# [duplicate]

Tags:

c#

linq

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

E.g. suppose

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

I want to call something like

my2dArray.flatten()

which would yield

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

Any ideas?

like image 835
Cedric Druck Avatar asked Sep 15 '15 13:09

Cedric Druck


1 Answers

You can use SelectMany

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

This will work with a jagged array like in your example, but not with a 2D array like

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

But in that case you can iterate the values like this

foreach(var item in my2dArray)
    Console.WriteLine(item);
like image 174
juharr Avatar answered Oct 14 '22 17:10

juharr