我在下面有一些用于按钮单击事件的代码,它使用冒泡排序。我有点不清楚用途。尝试按升序对数组进行排序。此外,我必须使用 foreach 并且需要以某种方式从中获取索引。尝试 int z = a.GetEnumerator(); 不起作用。int k = 0;//作弊以使代码正常工作
int k = 0;//Cheat to get code working
foreach (BankAccount BankAccount in a)
//for (int i = 0; i < a.Length; i++)
{
//int z = a.GetEnumerator();
lstBefore.Items.Add(a[k].show());
k += 1;//Cheat to get code working
}
//if (a[0] is IComparable)
//{
//Sort.BubbleSort(a);//Sort a
k = 0;//Cheat to get code working
for (int i = 0; i < a.Length; i++)
{
lstAfter.Items.Add(a[k].show());
//else MessageBox.Show("unable to sort");
k += 1;//Cheat to get code working
}
//}
//else MessageBox.Show("unable to sort");
class Sort : IComparable
{
public static void BubbleSort(IComparable[] arr)
{
bool swap = true;
IComparable temp;
for (int i = 0; swap; i++)
{
swap = false;
for (int j = 0; j < (arr.Length - (i + 1)); j++)
{
//int test = arr[j].CompareTo(arr[j + 1]);
if (arr[j].CompareTo(arr[j + 1]) > 0)
//If this balance is < than next balance
{
temp = (IComparable)arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swap = true;
}
}
}
}
}
我也有
public class BankAccount : IComparable, IComparable<BankAccount>//Class BackAccount - //Icomarable
{
private decimal balance;
private string FullName;
//...
public int CompareTo(BankAccount that)//Compare To
{
if (this.balance > that.balance) return -1;//If this balance is > than next balance
if (this.balance == that.balance) return 0;//If this balance is = to next balance
return 1;//If this balance is < than next balance
//return this.balance.CompareTo(that.balance);
}
}
Thanks,