1

How ca I delete an entire row from an 2d array? I want to keep deleting 1 row from the array shipPosition,untill it doesn`t have any elements.

shipPosition -= shipPosition[0,0] 

and

shipPosition -= shipPosition[0,1]

E.g.

int[,] shipPosition = new int[3, 2];

shipPosition[0, 0] = 2;
shipPosition[0, 1] = 3;
shipPosition[1, 0] = 4;
shipPosition[1, 1] = 5;
shipPosition[2, 0] = 6;
shipPosition[2, 1] = 7;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
john
  • 73
  • 7
  • Does this answer your question? [Iterate through 2 dimensional array c#](https://stackoverflow.com/questions/8184306/iterate-through-2-dimensional-array-c-sharp) – Drag and Drop Mar 23 '20 at 12:26
  • 1
    Does this answer your question? [How can I delete rows and columns from 2D array in C#?](https://stackoverflow.com/questions/26303030/how-can-i-delete-rows-and-columns-from-2d-array-in-c) – gwt Mar 23 '20 at 12:28
  • Here is the answer: https://stackoverflow.com/questions/26303030/how-can-i-delete-rows-and-columns-from-2d-array-in-c –  Mar 23 '20 at 12:33

3 Answers3

1

In C# arrays (of whatever dimension) are of fixed size. You can change the content of an element, but you can't add or remove elements (and therefor rows).

You'll need to write (or find from a third party) a class that manages this for you (much like List<T> effectively allows changing the number of elements in a 1D array).

Jasper Kent
  • 3,546
  • 15
  • 21
1

I suggest to change collection's type: List<int[]> (list of arrays) instead of 2d array:

  List<int[]> shipPosition = new List<int[]>() {
    new int[] {2, 3}, // 1st line 
    new int[] {4, 5}, // 2nd line 
    new int[] {6, 7}, // ...  
  };  

Now, if you want to remove enrire row (say the top one, {2, 3}), just do it

 shipPosition.RemoveAt(0);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Approach with for loop

public static int[,] DeleteRow(int rowDeleteIndex, int[,] sourceArray)
{
    int rows = sourceArray.GetLength(0);
    int cols = sourceArray.GetLength(1);
    int[,] result = new int[rows - 1, cols];
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            if (i != rowDeleteIndex)
            {
                result[i >= rowDeleteIndex ? i - 1 : i, j] = sourceArray[i, j];
            }
        }
    }
    return result;
}

so you can

int[,] shipPosition = new int[3, 2] { { 2, 3 }, { 4, 5 }, { 6, 7 } };
int[,] result = DeleteRow(1, shipPosition);

https://dotnetfiddle.net/rsrjoZ

fubo
  • 44,811
  • 17
  • 103
  • 137