Swap Elements in a 2D Array C#

笑着哭i 提交于 2019-12-02 11:48:31

问题


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.



来源:https://stackoverflow.com/questions/5375233/swap-elements-in-a-2d-array-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!