Board index » delphi » TList.Sort - Problem sorting a list

TList.Sort - Problem sorting a list

How can I sort a Tlist object.

For example this TList object:

type
  PMyList = ^AList;
  AList = record
    I: Integer;
    C: Char;
  end;
var
  MyList: TList;
begin
......
     MyList.Sort; isn't enough.
end;

Please sent some samples.

 

Re:TList.Sort - Problem sorting a list


You must provide the TList a comparaision function (so it can decide which
comes before which),

create a function (not a method, must be a good old function)

 // you can change the func`s name, and the parameters names, but you *must*
create a function having 2 parameters of "pointer" type
function SortMyListItem(item1,item2:Pointer):integer;
begin
// sort by integer ascending;
    if PMyList(item1)^.I < PMyList(item2)^.I then
        result := -1 else
            if PMyList(item1)^.I > PMyList(item2)^.I
                then result := 1
                else result := 0;
end;

of couse, if you want to sort by char, modify the code accordingly, you can
handle both situation by having as many of these function as you want;

To sort, symply use

MyList.Sort(SortMyListItem); // passes the comparaision function to the
internal TList sort engine.

Hope it helps

Cheers

Eric Boisvert
Quebec City

Aljosa Turk <i...@siol.net> a crit dans le message :
JUcF3.84$4j1.32...@news.siol.net...

Quote
> How can I sort a Tlist object.

> For example this TList object:

> type
>   PMyList = ^AList;
>   AList = record
>     I: Integer;
>     C: Char;
>   end;
> var
>   MyList: TList;
> begin
> ......
>      MyList.Sort; isn't enough.
> end;

> Please sent some samples.

Other Threads