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;
3

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.