Delphi coding hints and tips.
Sorting a TList
TList is a class that is used to store and maintain a list of objects, or put another way is a list of pointers. What the pointers point to is up to us, the user of the TList. Thus TList has no way of knowing how to compare any two items in its list, we have to provide it with a way to compare two items when sorting the list. The TList.Sort method has one parameter, a procedure of type TListSortCompare which we need to code in order to sort a TList.
For example assume TList holds pointers to the following Pascal record type,
type
TRec=record
Str:String;
Int:Integer;
end;
PRec=^TRec;
Then to sort the TList into ascending order based on Str we would need the following compare function:
function CompareString(Item1, Item2: Pointer): Integer; begin if PRec(Item1)^.Str<PRec(Item2)^.Str then Result:=-1; if PRec(Item1)^.Str=PRec(Item2)^.Str then Result:=0; if PRec(Item1)^.Str>PRec(Item2)^.Str then Result:=+1; end;
And the following would call the TList.Sort method would actually execute the sort:
FList.Sort(CompareString);
The compare function is a stand alone standard function and not a method within a class. It returns an integer value < 0 if Item1 is less than Item2, 0 if they are equal and > 0 if Item1 is greater than Item2.
Downloadable example project:
sortingtlist.zip (3,793 bytes)


