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

后端 未结 6 1821
夕颜
夕颜 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:21

    Why not make a generic extension method?

        public static T[] GetRow(this T[,] input2DArray, int row) where T : IComparable
        {
            var width = input2DArray.GetLength(0);
            var height = input2DArray.GetLength(1);
    
            if (row >= height)
                throw new IndexOutOfRangeException("Row Index Out of Range");
            // Ensures the row requested is within the range of the 2-d array
    
    
            var returnRow = new T[width];
            for(var i = 0; i < width; i++)
                returnRow[i] = input2DArray[i, row];
    
            return returnRow;
        }
    

    Like this all you have to code is:

    array2D = new double[,];
    // ... fill array here
    var row = array2D.GetRow(4) // Implies getting 5th row of the 2-D Array
    

    This is useful if you're trying to chain methods after obtaining a row and could be helpful with LINQ commands as well.

提交回复
热议问题