How to remove rows and columns from a 2D array in C #?

How to remove a specific row and column from a 2D array in C #?

int[,] array= {{1,2,3},{4,5,6},{7,8,9}};

let's say I want to delete the row i and the column i (skipping them) ... for the nXn array is not just 3x3 and save the remaining array in a new array ... so the output will be:

{5,6},{8,9}
+4
source share
4 answers

There is no built-in way to do this, you can do it yourself:

 static void Main()
        {
            int[,] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
            var trim = TrimArray(0, 2, array);
        }


        public static int[,] TrimArray(int rowToRemove, int columnToRemove, int[,] originalArray)
        {
            int[,] result = new int[originalArray.GetLength(0) - 1, originalArray.GetLength(1) - 1];

            for (int i = 0, j = 0; i < originalArray.GetLength(0); i++)
            {
                if (i == rowToRemove)
                    continue;

                for (int k = 0, u = 0; k < originalArray.GetLength(1); k++)
                {
                    if (k == columnToRemove)
                        continue;

                    result[j, u] = originalArray[i, k];
                    u++;
                }
                j++;
            }

            return result;
        }
+3
source

No, arrays do not allow this. You can create your own data structure for yourself, but it will not be so simple (unlike what you would like, for example, to delete rows).

, 2D- . , .

+1

Very simple logic. Just play with the loop:

int[,] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[,] arrayskip = new int[array.GetLength(0) - 1, array.GetLength(1) - 1];

for (int i = 1; i < array.GetLength(0); i++)
{
    for (int j = 1; j < array.GetLength(1); j++)
    {
        arrayskip[i - 1, j - 1] = array[i, j];
    }
}
+1
source

I created this method, I'll see

 public static double[,] fillNewArr(double[,] originalArr, int row, int col)
    {
        double[,] tempArray = new double[originalArr.GetLength(0) - 1, originalArr.GetLength(1) - 1];
        int newRow = 0;
        int newCol = 0;
        for (int i = 0; i < originalArr.GetLength(0); i++)
        {
            for (int j = 0; j < originalArr.GetLength(1); j++)
            {
                if(i != row && j != col)
                {
                    tempArray[newRow, newCol] = originalArr[i, j];
                    newRow++;
                    newCol++;
                }

            }

        }
        return tempArray;

    }

having some out of reach, obviously why, but I'm trying to get there ...

0
source

All Articles