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!

1
  • 1
    You could use a List<string[]>. This would then give you the Remove and RemoveAt methods, and the management of gaps would occur for you. Commented Mar 21, 2011 at 10:25

3 Answers 3

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];
     }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.