Reputation: 6138
I'm having trouble sorting a string list in Delphi XE2. Here's an example:
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;
The problem, as far as I understand, is due to the fact that TStringList.Sorted
is never set to true (neither directly nor using SetSorted). Is it just me or is it a bug?
Upvotes: 2
Views: 363
Reputation: 125669
There's nothing in the Classes
unit for TStringList.Sort
that should make you expect it to change the property. The TStringList.Sort
method simply calls CustomSort
with the default sorting function. It's not an indicator of the state of the list (sorted or unsorted); it merely determines whether the list is sorted using the internal sort algorithm and new items are added to the proper location instead of the end. From the documentation:
Specifies whether the strings in the list should be automatically sorted.
Set Sorted to true to cause the strings in the list to be automatically sorted in ascending order. Set Sorted to false to allow strings to remain where they are inserted. When Sorted is false, the strings in the list can be put in ascending order at any time by calling the Sort method.
When Sorted is true, do not use Insert to add strings to the list. Instead, use Add, which will insert the new strings in the appropriate position. When Sorted is false, use Insert to add strings to an arbitrary position in the list, or Add to add strings to the end of the list
You're using it wrong in the first place, though. Simply add all of your strings to the StringList
, and then set Sorted := True;
. It will properly set the property value and call the internal Sort
method for you automatically.
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;
(You particularly don't want to call Sort()
after every single item is added; that's extremely slow and inefficient.)
Upvotes: 6