交换2D数组C#中的元素 [英] Swap Elements in a 2D Array C#

查看:189
本文介绍了交换2D数组C#中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#,我对该语言还很陌生,但是之前我使用过类似的语言,所以我了解基本语法.

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

我有一个Object类型的2D数组. (X代表什么值,Y是什么记录)它在列0和1中存储两个字符串,在列2中存储一个MessageBoxIcon,在列3中存储一个MessageBoxButtons.

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.

每次对数组进行更改时,我都会在第1列中填充一个listBox. (使用循环)我对此系统感到满意. 我已经在列表框的侧面放置了+和-按钮,但是我无法弄清楚如何在其后面编写代码.

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.

我想要它,这样当我单击+按钮时,它将当前选择的记录增加到一个记录. (即,它减小了它的Y位置,并增加了它上方记录的Y坐标).它需要碰触与该记录相关的所有值.

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.

推荐答案

这需要以旧的方式完成,以交换两个变量的值:

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

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

但是,由于a和b是2d数组的行,因此必须一次完成一个元素.

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.

这篇关于交换2D数组C#中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆