2

Can we initialize an array of double[][][] as double[1][2][3] (this is not the correct syntax) using linq.

using for loop one way is

double[][][] myarr = new double[1][][];
for(int i=0; i<1; i++)
{
    myarr[i] = new double[2][];
    for(int j=0; j<2; j++)
    {
         myarr[i][j] = new double[3];
    }
}

but i want a cleaner code. I tried Select but it only fills first level. How to go about it. Thanks

& btw this is not homework!!

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208

1 Answers1

4
double[][][] threeDimensionArray = 
  Enumerable.Range(0, 1)
            .Select(h1 => Enumerable.Range(0, 2)
                                    .Select(h2 => new double[3])
                                    .ToArray())
            .ToArray();

But this requires multiple ToArray() calls which doing memory copy (see implementaiton below) so for big number of items it would not be efficient so such kind of "elegant" solution is not for free. BTW, I would prefer for loop solution.

Enumerable.ToArray() implementation: (credits to ILSpy)

// System.Linq.Enumerable
public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }

     // sll: see implementation of Buffer.ToArray() below
    return new Buffer<TSource>(source).ToArray();
}

// System.Linq.Buffer<TElement>
internal TElement[] ToArray()
{
    if (this.count == 0)
    {
        return new TElement[0];
    }
    if (this.items.Length == this.count)
    {
        return this.items;
    }
    TElement[] array = new TElement[this.count];
    Array.Copy(this.items, 0, array, 0, this.count);
    return array;
}
sll
  • 61,540
  • 22
  • 104
  • 156