Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

.net

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 doing:

double[] fourthRow = new double[]{rectArray[3,0],
                                  rectArray[3,1], 
                                  rectArray[3,2]};

Is it possible someway? Even using a Marshal.Something approach?

Thanks!

like image 746
abenci Avatar asked Jun 04 '10 19:06

abenci


People also ask

How do you get the second row of a two-dimensional array?

We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.

How do you calculate a double array?

By Row Major Order If array is declared by a[m][n] where m is the number of rows while n is the number of columns, then address of an element a[i][j] of the array stored in row major order is calculated as, Address(a[i][j]) = B. A. + (i * n + j) * size.


1 Answers

Why not make a generic extension method?

    public static T[] GetRow<T>(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.

like image 100
The Don Avatar answered Oct 11 '22 08:10

The Don