简体   繁体   English

排序C#ListBox项目

[英]Sort C# ListBox Items

I'm using C# Adapter method, I add elements to a list and after that I call that list to fill a listbox, here is my button for do that: 我正在使用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--;

    }
  }

}

结果

This is what I get, it's ok but I want to know if exists a way to do this like this example: 这是我得到的,没关系,但是我想知道是否存在一种执行此示例的方法:

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

If you see my code I have a variable x , this variable is the total number of costumers, so I think that my sort has to start with this variable, but I don't know exactly how to do it, what can I do? 如果您看到我的代码,则有一个变量x ,该变量是客户的总数,因此我认为我的排序必须以该变量开头,但是我不知道该怎么做,我该怎么办?

Reverse the list and start counting untill you reach the end: 反转列表并开始计数,直到到达终点为止:

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

you can probably reverse (Using the Reverse method) your list "customersSaldo" before adding it, and then use the variable 'x' in increment order. 您可以在添加列表“ customersSaldo”之前将其反转(使用Reverse方法),然后按递增顺序使用变量“ x”。

https://msdn.microsoft.com/en-us/library/b0axc2h2(v=vs.110).aspx 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