【发布时间】:2026-02-22 07:35:01
【问题描述】:
我正在反序列化一个包含记录的文本文件,并将记录转换为 Product 对象。我将对象添加到列表框并按第一个字段排序,即价格并设置为双精度。我将列表框设置为排序:
listBox1.Sorted = true;
但列表框仅按第一个数字排序,即,它将 15.00 美元放在 3.00 美元之上。按整个价格而不是第一个数字排序的最佳方法是什么?
【问题讨论】:
我正在反序列化一个包含记录的文本文件,并将记录转换为 Product 对象。我将对象添加到列表框并按第一个字段排序,即价格并设置为双精度。我将列表框设置为排序:
listBox1.Sorted = true;
但列表框仅按第一个数字排序,即,它将 15.00 美元放在 3.00 美元之上。按整个价格而不是第一个数字排序的最佳方法是什么?
【问题讨论】:
问题是它不是按数字排序,而是按字母排序,
请设置listBox1.Sorted = false;
使用 sort method 开始按价格对您的产品列表进行排序,然后将每个元素添加到控件。
【讨论】:
我想你必须从 ListBox 派生才能这样做。覆盖它的void Sort() 方法就可以了:
public class AlphabeticalSortedListBox : ListBox {
public AlphabeticalSortedListBox() : base() {
Sorted = true;
}
protected override void Sort() {
// apply your sorting algorithm on this.Items here.
// You might want to use an algorithm that does well
// in the best case (e.g. insertion sort [O(n)] to make it easy)
// because in the common situation we have an almost sorted list of Items
}
}
【讨论】: