2
votes

I have a multidimensional double array with any number of rows and columns:

var values = new double[rows, columns];

I also have a list of double arrays:

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

Now, I would like to add each column in the multidimensional array to the list. How do I do that? I wrote this to illustrate what I want, but it does not work as I am violation the syntax.

for (int i = 0; i < columns; i++)
{
    doubleList.Add(values[:,i];
}
3

3 Answers

3
votes
var values = new double[rows, columns];
var doubleList = new List<double[]>();

for (int i = 0; i < columns; i++)
{
    var tmpArray = new double[rows];
    for (int j = 0; j < rows; i++)
    {
        tmpArray[j] = values[j, i];
    }
    doubleList.Add(tmpArray);
}
2
votes

You will need to create a new array for each column and copy each value to it.
Either with a simple for-loop (like the other answers show) or with LINQ:

for (int i = 0; i < columns; i++)
{
    double[] column = Enumerable.Range(0, rows)
        .Select(row => values[row, i]).ToArray();
    doubleList.Add(column);
}
2
votes

With the approach you were taking:

for(int i = 0; i != columns; ++i)
{
    var arr = new double[rows];
    for(var j = 0; j != rows; ++j)
        arr[j] = values[j, i];
    doubleList.Add(arr);
}

Build up the each array, per row, then add it.

Another approach would be:

var doubleList = Enumerable.Range(0, columns).Select(
  i => Enumerable.Range(0, rows).Select(
    j => values[j, i]).ToArray()
  ).ToList()

Which some would consider more expressive in defining what is taken (values[j, i] for a sequence of i inner sequence of j) and what is done with them (put each inner result into an array and the result of that into a list).