{-----------------------------------------------------------------------------
Author: DelphiDeveloper 05.02.22
Purpose: Sort with TList
-----------------------------------------------------------------------------}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TDAddress =
class
SValue:
string;
IValue: integer;
PADR: Pointer;
end;
TForm1 =
class(TForm)
BtnCreateTheList: TButton;
BtnShowList: TButton;
ListBox1: TListBox;
RGrpSort: TRadioGroup;
BtnSort: TButton;
procedure BtnCreateTheListClick(Sender: TObject);
procedure BtnShowListClick(Sender: TObject);
procedure BtnSortClick(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
myList: Tlist;
procedure ClearList;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.BtnCreateTheListClick(Sender: TObject);
var aAdrObj: TDAddress;
I: integer;
begin
myList := TList.create;
// fuelle Liste mit beispielwerten
for i := 1
to 5
do
begin
aAdrObj := TDAddress.Create;
aAdrObj.SValue := chr(random(20) + 65);
aAdrObj.IValue := random(10);
MyList.Add(aAdrObj);
end;
end;
procedure TForm1.ClearList;
var I: integer;
begin
// erst die Objekte freigeben
if assigned(MyList)
then
begin
for i := 0
to myList.Count - 1
do
if MyList.Items[i] <>
nil then
TDAddress(myList.Items[i]).Free;
//und jetzt die Liste
MyList.Clear;
end;
end;
procedure TForm1.BtnShowListClick(Sender: TObject);
var i: integer;
begin
// nur um anzuzeigen was in der Liste steht
ListBox1.Clear;
for i := 0
to myList.Count - 1
do
begin
ListBox1.Items.Add(Inttostr(TDAddress(myList[i]).IValue) +
'
' + TDAddress(myList[i]).SValue);
end;
end;
function SortierenString(item1,item2:pointer):integer;
begin
// intern wird quicksort algo verwendet siehe OH
// sortierung von strings
result:=CompareText( TDAddress(Item1).SValue, (TDAddress(Item2).SValue));
end;
function SortierenInteger(item1,item2:pointer):integer;
begin
// intern wird quicksort algo verwendet siehe OH
// sortierung von integerwerten
result:=( TDAddress(Item1).iValue - (TDAddress(Item2).iValue));
end;
procedure TForm1.BtnSortClick(Sender: TObject);
begin
case RGrpSort.ItemIndex
of
0: MyList.Sort( SortierenInteger);
1: MyList.Sort( SortierenString);
end;
// neu anzeigen
BtnShowList.OnClick(sender);
end;
end.