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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With