Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Library: Sonstiges (https://www.delphipraxis.net/45-library-sonstiges/)
-   -   Delphi TStrings sortieren (https://www.delphipraxis.net/40816-tstrings-sortieren.html)

shmia 21. Feb 2005 15:03


TStrings sortieren
 
Nicht alle Klassen, die von TStrings abgeleitet sind, können ohne weiteres sortiert werden.
(Die Sort-Methode gibt es erst ab TStringList)
Delphi-Quellcode:
//Beispiel
begin
  Memo1.Lines.Sort; // geht nicht!!
end;
Deshalb muss man alle Strings in ein TStringList-Objekt umkopieren, dort sortieren und wieder zurückkopieren.
Dabei hilft die Procedure SortTStrings:
Delphi-Quellcode:
unit USortUtil;

interface
uses Classes;

procedure SortTStrings(Strings:TStrings; Duplicates:TDuplicates);

implementation

procedure SortTStrings(Strings:TStrings; Duplicates:TDuplicates);
var
  tmp: TStringList;
begin
  Assert(Assigned(Strings), 'SortTStrings: invalid arg');
  if Strings is TStringList then
  begin
    TStringList(Strings).Duplicates := Duplicates;
    TStringList(Strings).Sort;
  end else
  begin
    tmp := TStringList.Create;
    try
      tmp.Duplicates := Duplicates;
      tmp.Sorted := True;

      // make a sorted copy
      tmp.Assign(Strings);
      // copy back
      Strings.Assign(tmp);
    finally
      tmp.Free;
    end;
  end;
end;
end.
Und zu guter Letzt noch ein Beispiel:
Delphi-Quellcode:
uses USortUtil;
...
...
begin
  SortTStrings(Memo1.Lines, [dupAccept]);
end;
[edit=Matze]Code formatiert. Mfg, Matze[/edit]


Alle Zeitangaben in WEZ +1. Es ist jetzt 18:36 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz