Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete rows and columns from 2D array in C#?

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

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

lets say I want to delete row i and column i (skipping them) ... for nXn array not just 3x3 and store the remaining array in a new array... so the output would be:

{5,6},{8,9}
like image 587
WT86 Avatar asked Oct 10 '14 15:10

WT86


2 Answers

There's no built-in way to do that, 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;
        }
like image 83
brz Avatar answered Oct 27 '22 23:10

brz


No, arrays don't let you do that. You could make your own data structure for that, but it's not going to be exactly simple (unlike if you only wanted to be able to remove rows, for example).

For simple operations, it would be quite enough to build a class on top of an underlying array, and handle the re-indexing to map the virtual 2D array to the physical array underneath. But it's going to get a bit tricky as you combine removals and additions, and deform the array overall.

like image 29
Luaan Avatar answered Oct 27 '22 23:10

Luaan