Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list of arrays into a multidimensional array

I need to convert the following collection into double[,]:

 var ret = new List<double[]>();

All the arrays in the list have the same length. The simplest approach, ret.ToArray(), produces double[][], which is not what I want. Of course, I can create a new array manually, and copy numbers over in a loop, but is there a more elegant way?

Edit: my library is invoked from a different language, Mathematica, which has not been developed in .Net. I don't think that language can utilize jagged arrays. I do have to return a multidimensional array.

like image 420
Arne Lund Avatar asked Mar 19 '12 17:03

Arne Lund


1 Answers

I don't believe there's anything built into the framework to do this - even Array.Copy fails in this case. However, it's easy to write the code to do it by looping:

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        List<int[]> list = new List<int[]>
        {
            new[] { 1, 2, 3 },
            new[] { 4, 5, 6 },
        };

        int[,] array = CreateRectangularArray(list);
        foreach (int x in array)
        {
            Console.WriteLine(x); // 1, 2, 3, 4, 5, 6
        }
        Console.WriteLine(array[1, 2]); // 6
    }

    static T[,] CreateRectangularArray<T>(IList<T[]> arrays)
    {
        // TODO: Validation and special-casing for arrays.Count == 0
        int minorLength = arrays[0].Length;
        T[,] ret = new T[arrays.Count, minorLength];
        for (int i = 0; i < arrays.Count; i++)
        {
            var array = arrays[i];
            if (array.Length != minorLength)
            {
                throw new ArgumentException
                    ("All arrays must be the same length");
            }
            for (int j = 0; j < minorLength; j++)
            {
                ret[i, j] = array[j];
            }
        }
        return ret;
    }

}
like image 137
Jon Skeet Avatar answered Oct 05 '22 20:10

Jon Skeet