 |
BorlandTalk.com Borland discussion newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Dave Norton Guest
|
Posted: Wed Jul 30, 2003 6:33 pm Post subject: How to sort a TList? |
|
|
How to sort a TList? I can't figure out how to write a sort
function that compiles and access fields in TMyType.
type
pTMyType = ^TMyType;
TMyType = class(TObject)
public
fString1 : string;
fString2 : string;
end;
function MySort(Item1, Item2: Pointer): Integer;
fMyTypeList : TList;
..
..
fMyTypeList := TList.Create;
..
..
fMyTypeList.Add(anItem1);
fMyTypeList.Add(anItem2);
..
..
fMyTypeList.Sort(MySort); // or fMyTypeList.Sort(@MySort);
..
..
//______________________________________________________________________
function MySort(Item1, Item2: Pointer): Integer;
var
begin
// What to I write here? I've snipped out most of my attempts.
// This is similar to the example in Delphi help, but doesn't compile:
Result := CompareText((Item1 as TMyType).fString1, (Item2 as
TMyType).fString2);
end;
Here is the example from the Delphi help. The Sort function is _not_
called with the 'CompareNames' function - is this a misprint?
function CompareNames(Item1, Item2: Pointer): Integer;
begin
Result := CompareText((Item1 as TComponent).Name, (Item2 as
TComponent).Name);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
List1.Sort(@CompareText);
end;
Summary: How to write a compare function for TList.Sort?
Thanks much!
|
|
| Back to top |
|
 |
Jens Gruschel Guest
|
Posted: Wed Jul 30, 2003 7:28 pm Post subject: Re: How to sort a TList? |
|
|
| Quote: | pTMyType = ^TMyType;
|
First of all, this line makes no sense. Objects already are references, so
you need no pointers for classes (except if you need pointers to pointers,
but this is used very rarely in Delphi).
| Quote: | function MySort(Item1, Item2: Pointer): Integer;
begin
Result := CompareText((Item1 as TMyType).fString1, (Item2 as
TMyType).fString2);
end;
|
looks okay to me.
If you are sure both items are of type TMyType it's faster to cast the
pointer like this:
Result := CompareText(TMyType(Item1).fString1, TMyType(Item2).fString2);
| Quote: | List1.Sort(MySort);
|
should work (without the @).
Jens
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|