RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TStringList.Sort Method

Sorts the strings in the list in ascending order.

Pascal
procedure Sort; virtual;
C++
virtual __fastcall Sort();

Call Sort to sort the strings in a list that has the Sorted property set to false. String lists with the Sorted property set to true are automatically sorted.

Note: Sort uses AnsiCompareStr to sort the strings when CaseSensitive is true and AnsiCompareText when CaseSensitive is false. To provide your own comparison operator instead, use the CustomSort method.
 

C++ Examples: 

 

/*
This example uses a list box and a label on a form. When the
application runs, a string list object is created and three
strings are added to it. The Find method searches the 
strings to look for a match with the string ‘Flowers’. If
the string is found, all the strings in the string list are
added to the list box, and the index value of the ‘Flowers’
string appears in the caption of the label control.
*/

#include <memory>       //for STL auto_ptr class

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  int Index;
  std::auto_ptr<TStringList> MyList(new TStringList());
  MyList->Add("Animals");
  MyList->Add("Flowers");
  MyList->Add("Ocean");
  MyList->Sort(); // Find will only work on sorted lists
  if (MyList->Find("Flowers", Index))
  {
    ListBox1->Items->AddStrings(MyList.get());
    Label1->Caption = "Flowers has an index value of " + AnsiString(Index);
  }
}

 

Delphi Examples: 

{
This example uses a list box and a label on a form. When the
application runs, a string list object is created and three
strings are added to it. The Find method searches the 
strings to look for a match with the string ‘Flowers’. If
the string is found, all the strings in the string list are
added to the list box, and the index value of the ‘Flowers’
string appears in the caption of the label control.
} 
procedure TForm1.FormCreate(Sender: TObject);
var
  MyList: TStringList;
  Index: Integer;
begin
  MyList := TStringList.Create;
  try
    MyList.Add('Animals');
    MyList.Add('Flowers');
    MyList.Add('Cars');
    MyList.Sort;   { Find will only work on sorted lists! }
    if MyList.Find('Flowers', Index) then
    begin
      ListBox1.Items.AddStrings(MyList);
      Label1.Caption := 'Flowers has an index value of ' + IntToStr(Index);
    end;
  finally
    MyList.Free;
  end;
end; 

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!