HenryM2
asked on
Delphi What is the best way to sort an Array of String
What is the fastest sort to alphabetically sort an Array of String. The arrays will generally be smalish, about 20 elements. I am using Delphi 2010 and beleve there is a built in function to do this, if so what is the function and how is it used?
If you are using D2010, try something like this
TArray.Sort<string>(YourAr ray , TDelegatedComparer<string> .Construct (
function(const Left, Right: string): Integer
begin
Result := TComparer<String>.Default. Compare(Le ft, Right);
end));
TArray.Sort<string>(YourAr
function(const Left, Right: string): Integer
begin
Result := TComparer<String>.Default.
end));
Here is tested example:
uses
Generics.Defaults,
Generics.Collections;
procedure TForm1.Button1Click(Sender : TObject);
var
StrArray: array of string;
begin
SetLength( StrArray, 3);
StrArray[0]:= 'Str 3';
StrArray[1]:= 'Str 2';
StrArray[2]:= 'Str 1';
TArray.Sort<string>(StrArr ay , TDelegatedComparer<string> .Construct (
function(const Left, Right: string): Integer
begin
Result := TComparer<String>.Default. Compare(Le ft, Right);
end));
end;
uses
Generics.Defaults,
Generics.Collections;
procedure TForm1.Button1Click(Sender
var
StrArray: array of string;
begin
SetLength( StrArray, 3);
StrArray[0]:= 'Str 3';
StrArray[1]:= 'Str 2';
StrArray[2]:= 'Str 1';
TArray.Sort<string>(StrArr
function(const Left, Right: string): Integer
begin
Result := TComparer<String>.Default.
end));
end;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I am having difficulty to get it working. I have not used TStrings before, is there a Unit to be listes in Uses for this. I added the Uses caluses that you used but get Incompatible type error in line "SetLength( StrArray, 3);"
I also get [DCC Error] SiteDesignerMainUnt.pas(97 10): E2250 There is no overloaded version of 'TArray.Sort<System.string >' that can be called with these arguments for line " TArray.Sort<string>(StrArr ay);"
I also get [DCC Error] SiteDesignerMainUnt.pas(97
ASKER
Sorry, my previous commnet = false alarm, now working.
ASKER
Thanks, works great.
var
StrArray: TStrings;
begin
StrArray:= TStringList.Create;
try
StrArray.Add( 'Str 1' );
StrArray.Add( 'Str 2' );
StrArray.Add( 'Str 3' );
StrArray.Sort; <------------------------
finally
StrArray.Free;
end;