1. Home
  2. Computing & Technology
  3. Delphi Programming

How to sort items in a TList object

By Zarko Gajic, About.com

When you are working with a TList object and want to sort the (list) items based on a custom criteria, you can use the next code...

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

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2003 Delphi Tips
  7. How to sort items in a TList object

©2009 About.com, a part of The New York Times Company.

All rights reserved.