Można też posortować elementy listy zwracanej przez DirectoryListing
. Przykład prostego sortowania:
type
TSortDirection = (sdAsc, sdDesc);
TIdFTPListItemsHelper = class helper for TIdFTPListItems
strict private
procedure Swap(AIndex1, AIndex2: Integer);
function Compare(AVal, BVal: Variant; ASortDirection: TSortDirection = sdAsc): Boolean;
public
procedure SortByModifiedDate(ASortDirection: TSortDirection = sdAsc);
procedure SortByName(ASortDirection: TSortDirection = sdAsc);
procedure SortBySize(ASortDirection: TSortDirection = sdAsc);
end;
//...
implementation
{$R *.dfm}
{
procedure TIdFTPListItemsHelper.Swap(AIndex1, AIndex2: Integer); //stara wersja z wkurzającym każdorazowym Create
tmpItem: TIdFTPListItem;
begin
tmpItem:= TIdFTPListItem.Create(nil);
try
tmpItem.Assign(Self.Items[AIndex1]);
Self.Items[AIndex1]:= Self.Items[AIndex2];
Self.Items[AIndex2]:= tmpItem;
finally
tmpItem.Free;
end;
end; }
procedure TIdFTPListItemsHelper.Swap(AIndex1, AIndex2: Integer); //nowa wersja pozbawiona powyższej wady
begin
Self.Items[AIndex1].Index:= AIndex2;
end;
function TIdFTPListItemsHelper.Compare(AVal, BVal: Variant; ASortDirection: TSortDirection = sdAsc): Boolean;
begin
if (ASortDirection = sdAsc) then
result:= (AVal > BVal)
else
result:= (AVal < BVal)
end;
procedure TIdFTPListItemsHelper.SortByModifiedDate(ASortDirection: TSortDirection = sdAsc);
var
i, j: Integer;
begin
for i:= Pred(Self.Count) downto 0 do
for j:= 0 to Pred(i) do
if (Compare(Self.Items[j].ModifiedDate, Self.Items[j+1].ModifiedDate, ASortDirection)) then
Self.Swap(j, j+1);
end;
procedure TIdFTPListItemsHelper.SortByName(ASortDirection: TSortDirection = sdAsc);
var
i, j: Integer;
begin
for i:= Pred(Self.Count) downto 0 do
for j:= 0 to Pred(i) do
if (Compare(Self.Items[j].FileName, Self.Items[j+1].FileName, ASortDirection)) then
Self.Swap(j, j+1);
end;
procedure TIdFTPListItemsHelper.SortBySize(ASortDirection: TSortDirection = sdAsc);
var
i, j: Integer;
begin
for i:= Pred(Self.Count) downto 0 do
for j:= 0 to Pred(i) do
if (Compare(Self.Items[j].Size, Self.Items[j+1].Size, ASortDirection)) then
Self.Swap(j, j+1);
end;
I po wywołaniu List
możesz wywoływać jedną z metod:
IdFTP.DirectoryListing.SortByModifiedDate(sdDesc); //bez parametru lub z parametrem sdAsc sortowanie rosnace
IdFTP.DirectoryListing.SortByName(sdDesc);
IdFTP.DirectoryListing.SortBySize(sdDesc);