Swap Elements in a 2D Array C#

2019-02-28 10:43发布

问题:

I am using C#, I'm fairly new to the language but I have used similar languages before so I understand basic syntax.

I have a 2D array of type Object. (X represents what value and Y is what record) It stores two strings in columns 0 and 1 and a MessageBoxIcon in 2 and a MessageBoxButtons in 3.

I would like the ability to swap two records.

I populate a listBox with column 1 every time a change is made to the array. (using a loop) I am happy with this system. I have placed + and - buttons to the side of the listBox but I cannot figure out how to do the code behind it.

I want it so that when I click the + button it bumps the currently selected record up one record. (I.E. It decreases it's Y location and increase the Y coordinate of the record above it) It would need to bump all the values associated with that record.

Could someone provide me with a function to do this?

I hope I explained this well enough.

回答1:

This will need to be done in the old way for swapping two variable's values:

var t = a;
a = b;
b = t;

But, with a and b being rows of a 2d array this has to be done one element at a time.

public void Swap2DRows(Array a, int indexOne, int indexTwo) {
  if (a == null} { throw new ArgumentNullException("a"); }
  if (a.Rank != 2) { throw new InvalidOperationException("..."); }

  // Only support zero based:
  if (a.GetLowerBound(0) != 0) { throw new InvalidOperationException("..."); }
  if (a.GetLowerBound(1) != 0) { throw new InvalidOperationException("..."); }

  if (indexOne >= a.GetUpperBound(0)) { throw new InvalidOperationException("..."); }
  if (indexTwo >= a.GetUpperBound(0)) { throw new InvalidOperationException("..."); }

  for (int i = 0; i <= a.GetUpperBound(1); ++i) {
    var t = a[indexOne, i];
    a[indexOne, i] = a[indexTwo, i];
    a[indexTwo, i] = t;
  }
}

This could be generalised to handle arbitrary lower bounds.