是否可以使用自定义排序比较器对TListBox进行排序? [英] Is it possible to sort a TListBox using a custom sort comparator?
问题描述
我需要对TListBox进行排序,但是我意识到,如果要说要创建一个TStringList,对其进行排序,然后将这些项目复制到Listbox中,那么修改代码的工作量很大.进行大量工作的主要原因是,我在代码中有很多地方可以修改列表框的内容,我想我必须对其全部进行编辑以在添加,删除或进行其他操作时强制排序.>
我更喜欢让我只是将方法附加到列表框以某种方式使用我的自定义排序逻辑对其进行排序的东西.
有可能吗?
这没问题!看下面的代码:
function CompareDates(List:TStringList; Index1,Index2:Integer):整数;变种d1,d2:TDateTime;开始d1:= StrToDate(List [Index1]);d2:= StrToDate(List [Index2]);如果d1 <然后d2结果:= -1否则,如果d1>然后d2结果:= 1别的结果:= 0;结尾;过程TForm1.Button1Click(Sender:TObject);变种sl:TStringList;开始sl:= TStringList.Create;尝试sl.Assign(ListBox1.Items);sl.CustomSort(CompareDates);ListBox1.Items.Assign(sl);最后免费结尾;结尾;
I need to sort my TListBox but I realized it is a lot of work to modify my code if I were to say make a TStringList, sort it and then copy those items into the Listbox. The main reason it's a lot of work is that I have many places in the code where the listbox contents are modified and I guess I would have to edit them all to force a sort at the time they are added, deleted or whatever.
I would much prefer something that let me just attach a method to a listbox somehow to sort it using my custom sort logic.
Is it somehow possible?
This is no Problem! Look at this Code:
function CompareDates(List: TStringList; Index1, Index2: Integer): Integer;
var
d1, d2: TDateTime;
begin
d1 := StrToDate(List[Index1]);
d2 := StrToDate(List[Index2]);
if d1 < d2 then
Result := -1
else if d1 > d2 then
Result := 1
else
Result := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.Assign(ListBox1.Items);
sl.CustomSort(CompareDates);
ListBox1.Items.Assign(sl);
finally
sl.Free
end;
end;
这篇关于是否可以使用自定义排序比较器对TListBox进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!