Converting <T>[][] to <T>[] by extracting 1 element from the inner array

Is there a potential 1 liner that allows me to create a new 1 dimensional array from a certain index of the inner array of the 2D?

Example take the first element of each inner array:

double[][] array2D = new double[10][] // with inner arrays say double[5]
double[] array1D = new double[10];

for (int i=0; i<array2D.Length; i++)
{
    array1D[i] = array2D[i][0];
}
Jon Skeet
people
quotationmark

I'd just use LINQ. That won't "avoid loops" in terms of execution, but it'll avoid a loop in your source code:

// 1dArray isn't a valid identifier...
var singleArray = jaggedArray.Select(x => x[0]).ToArray();

Note that this relies on it being a jagged array (an array of arrays). It will not do what you expect for true multi-dimensional (rectangular) arrays.

Or slightly more efficiently:

var singleArray = Array.ConvertAll(jaggedArray, x => x[0]);

That's more efficient because it knows the output size to start with, and builds the array directly - but it's a bit less idiomatic than using LINQ these days (which is more generally applicable to all sequences, not just arrays).

people

See more on this question at Stackoverflow