2

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];
}
0

3 Answers 3

3
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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Ofc. iterate over each dimension. Just thought there was (or should be) a more elegant solution - maybe with LINQ.
@TimPohlmann An array is a collection too. LINQ works fine with arrays.
See Deniss_E's answer for a LINQ solution. LINQ does not work on arrays, though, which makes it a bit tricky.
@Dennis_E linq doesn't work well directly with multi-dimensional arrays, as your own answer makes use of. I prefer one extreme or the other (all linq or no linq) myself, but all three answers produce the same results.
2

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 Comments

Or doubleList=Enumerable.Range(0,columns).Select(col=>Enumerable.Range(0,rows).Select(row=>values[row,col]).ToArray()).ToList(); if you really hate for loops.
Or even var doubleList = (from c in Enumerable.Range(0, columns) select (from r in Enumerable.Range(0, rows) select values[r, c]).ToArray()).ToList(); ;)
2

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.