The following example code sorts the items in a list in alphabetical order based on their names. It assumes that the list contains only references to variables of type TMyListItem, where TMyListItem is defined as:
type
TMyListItem = record
Points : Integer;
Name: string[255] ;
end;
The CompareNames function performs the comparisons between objects in the list. The list is sorted when the user clicks a button.
~~~~~~~~~~~~~~~~~~~~~~~~~
function CompareNames(Item1, Item2: Pointer): Integer;
begin
Result := CompareText((Item1 as TMyListItem).Name,
(Item2 as TMyListItem).Name) ;
end;
procedure TForm1.Button1Click(Sender: TObject) ;
begin
List1.Sort(@CompareNames) ;
end;
{
Note: the Sort method needs a pointer to
a custom function (with the signature below)
that indicates how the items are to be ordered.
type
TListSortCompare = function (Item1,
Item2: Pointer): Integer;
Your sorting / comparison function should return
a positive value if Item1 is less than Item2,
0 if they are equal, and a negative value
if Item1 is greater than Item2.
}
~~~~~~~~~~~~~~~~~~~~~~~~~
Delphi tips navigator:
» Rounding control corners
« Match column title alignments with field alignments in DBGrid
