我在Delphi XE2中排序字符串列表时遇到问题.这是一个例子:
procedure AddText();
var
StrList: TStringList;
begin
StrList := TStringList.Create();
StrList.Add('Test1');
StrList.Sort();
WriteLn('Sorted: ' + BoolToStr(StrList.Sorted, true)); // Prints "Sorted: false"
StrList.Add('Test2');
StrList.Sort();
WriteLn('Sorted: ' + BoolToStr(StrList.Sorted, true)); // Prints "Sorted: false"
StrList.Add('Test3');
StrList.Free();
end;
Run Code Online (Sandbox Code Playgroud)
据我所知,问题是由于事实TStringList.Sorted永远不会设置为true(既不直接也不使用SetSorted).它只是我还是一个bug?
Classes单位中没有任何东西TStringList.Sort可以让你期望它改变财产.该TStringList.Sort方法只CustomSort使用默认排序函数调用.它不是列表状态的指示符(已排序或未排序); 它只是确定是否使用内部排序算法对列表进行排序,并将新项目添加到正确的位置而不是结尾.从文档:
指定列表中的字符串是否应自动排序.
将Sorted设置为true可使列表中的字符串按升序自动排序.将Sorted设置为false以允许字符串保留在插入位置.当Sorted为false时,可以通过调用Sort方法随时按升序放置列表中的字符串.
当Sorted为true时,请勿使用Insert将字符串添加到列表中.相反,使用Add,它会将新字符串插入适当的位置.当Sorted为false时,使用Insert将字符串添加到列表中的任意位置,或使用Add将字符串添加到列表末尾
不过,你首先使用它是错误的.只需将所有字符串添加到StringList,然后设置Sorted := True;.它将正确设置属性值并Sort自动为您调用内部方法.
procedure AddText();
var
StrList: TStringList;
begin
StrList := TStringList.Create();
StrList.Add('Test1');
StrList.Add('Test2');
StrList.Add('Test3');
StrList.Sorted := True;
// Do whatever
StrList.Free;
end;
Run Code Online (Sandbox Code Playgroud)
(你特别不希望Sort()在添加每个项目后调用;这非常慢且效率低.)