簡體   English   中英

排序C#ListBox項目

[英]Sort C# ListBox Items

我正在使用C#適配器方法,將元素添加到列表中,然后調用該列表以填充列表框,這是我要執行的按鈕:

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--;

    }
  }

}

結果

這是我得到的,沒關系,但是我想知道是否存在一種執行此示例的方法:

顧客#1 Saldo ...
顧客#2 Saldo ...
Costumer#3 Saldo ...

如果您看到我的代碼,則有一個變量x ,該變量是客戶的總數,因此我認為我的排序必須以該變量開頭,但是我不知道該怎么做,我該怎么辦?

反轉列表並開始計數,直到到達終點為止:

//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);

您可以在添加列表“ customersSaldo”之前將其反轉(使用Reverse方法),然后按遞增順序使用變量“ x”。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM