Mega Code Archive

 
Categories / Delphi / Strings
 

Sort all TStrings objects

Title: Sort all TStrings objects Question: Have you ever tried to sort the Lines of a memo control ? you can''t sort them in place because Lines is not a TStringList but a TMemoStrings // this code does not work: Memo1.Lines.Sort; // but we can do it this way SortTStrings(Memo1.Lines); Answer: procedure SortTStrings(Strings:TStrings); var tmp: TStringList; begin if Strings is TStringList then begin TStringList(Strings).Sort; end else begin tmp := TStringList.Create; try // make a copy tmp.Assign(Strings); // sort the copy tmp.Sort; // Strings.Assign(tmp); finally tmp.Free; end; end; end; //========================================================= // alternative implementation procedure SortTStrings(Strings:TStrings; Duplicates:TDuplicates); var tmp: TStringList; begin 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); // Strings.Assign(tmp); finally tmp.Free; end; end; end;