Getting a double[] row array of a double[,] rectangular array

后端 未结 6 1897
夕颜
夕颜 2021-02-13 13:43

Suppose you have an array like:

double[,] rectArray = new double[10,3];

Now you want the fouth row as a double[] array of 3 elements without do

6条回答
  •  不要未来只要你来
    2021-02-13 14:30

    Although this is an old thread, an addition to Joseph Sturtevants answer may be useful. His function crashes in case the matrix's first column is not zero, but another integer. This is e.g. always the case in case of retrieving data from Excel, like

    object[,] objects = null;
    Excel.Range range = worksheet.get_Range("A1", "C5");
    objects = range.Cells.Value; //columns start at 1, not at 0
    

    The GetRow function could be modified like this:

        public static T[] GetRow(T[,] matrix, int row, int firstColumn)
        {
            var columns = matrix.GetLength(1);
            var array = new T[columns];
            for (int i = firstColumn; i < firstColumn + columns; ++i)
                array[i-firstColumn] = matrix[row, i];
            return array;
        }
    

提交回复
热议问题