对C#ListBox项进行排序

时间:2016-11-05 17:33:44

标签: c# listbox

我正在使用C#Adapter方法,我将元素添加到列表中,之后我调用该列表来填充列表框,这是我的按钮:

private void button1_Click(object sender, EventArgs e) {
  listCustomers.Items.Clear();
  List < Customer > customers = CustomerList.GetCustomers();
  List < CustomerSaldo > customersSaldo = CustomerListSaldo.GetCustomers();
  int total = 0;
  int totalCustomer = 0;
  foreach(Customer customer in customers)
  total++;

  listCustomers.Items.Clear();

  totalCustomer = total;
  int x = totalCustomer;

  foreach(CustomerSaldo customer2 in customersSaldo) {
    if (x >= 1) {
      listCustomers.Items.Add("Costumer ID # " + x + " is: " + customer2.Saldo);
      x--;

    }
  }

}

Result

这就是我得到的,没关系,但我想知道是否存在这样做的方法:

  

客户#1 Saldo ...
  客户#2 Saldo ...
  客户#3 Saldo ......

如果你看到我的代码我有一个变量x,这个变量是客户的总数,所以我认为我的排序必须从这个变量开始,但我不知道该怎么做它,我该怎么办?

2 个答案:

答案 0 :(得分:1)

反转列表并开始计算,直到结束:

//Reverse the list
customersSaldo.Reverse();
//Add new items
for(int i = 0; i < customers.Count; i++) 
    listCustomers.Items.Add(string.Format("Costumer ID # {0} is: {1}", (i+1).ToString(), customersSaldo[i].Saldo);

答案 1 :(得分:0)

您可以撤销(使用反向方法)您的列表&#34; customersSaldo&#34;在添加之前,然后使用变量&#39; x&#39;按增量顺序。

https://msdn.microsoft.com/en-us/library/b0axc2h2(v=vs.110).aspx

相关问题