2

I am making a program that stores data in a 2D array. I would like to be able to delete rows from this array. I cannot figure out why this code doesn't work:

for (int n = index; n < a.GetUpperBound(1); ++n)
{
     for (int i = 0; i < a.GetUpperBound(0); ++i)
     {
         a[i, n] = a[i, n + 1];
     }
}

Could someone please help me out? I would like it to delete a single row and shuffle all the rows below it up one place. Thankyou!

YoshieMaster
  • 257
  • 3
  • 5
  • 13
  • 1
    You could use a `List`. This would then give you the `Remove` and `RemoveAt` methods, and the management of gaps would occur for you. – Adam Houldsworth Mar 21 '11 at 10:25

3 Answers3

2

you need to create a new array if you want to delete an item

try something like this

var arrayUpdated = new string[a.GetUpperBound(1)][a.GetUpperBound(0)-1];
for (int n = index; n < a.GetUpperBound(1); n++)
{
     for (int i = 0; i < a.GetUpperBound(0); i++)
     {
         arrayUpdated [i, n] = a[i, 1];
     }
}
Kimtho6
  • 6,154
  • 9
  • 40
  • 56
1

The nested for loop method here works well: https://stackoverflow.com/a/8000574

Here's a method that converts the outer loop of the [,] array method above to use linq. Using linq here is only recommended if you are also doing other things with linq during the traversal.

    public T[,] RemoveRow<T>(T[,] array2d, int rowToRemove)
    {
        var resultAsList = Enumerable
            .Range(0, array2d.GetLength(0))  // select all the rows available
            .Where(i => i != rowToRemove)    // except for the one we don't want
            .Select(i =>                     // select the results as a string[]
            {
                T[] row = new T[array2d.GetLength(1)];
                for (int column = 0; column < array2d.GetLength(1); column++)
                {
                    row[column] = array2d[i, column];
                }
                return row;
            }).ToList();

        // convert List<string[]> to string[,].
        return CreateRectangularArray(resultAsList); // CreateRectangularArray() can be copied from https://stackoverflow.com/a/9775057
    }

used Enumerable.Range to iterate all rows as done in https://stackoverflow.com/a/18673845

Community
  • 1
  • 1
ShawnFeatherly
  • 2,470
  • 27
  • 20
-1

Shouldn't ++i be i++? ++i increments before matrix operation is performed(ie pre-increment)

user623879
  • 4,066
  • 9
  • 38
  • 53