5

So, I want to sort array of strings by length (longer strings goes first) and if length is the same, then sort alphabetically. This is what is got so far:

uses
  System.Generics.Defaults
  , System.Types
  , System.Generics.Collections
  ;

procedure TForm2.FormCreate(Sender: TObject);
var
  _SortMe: TStringDynArray;
begin
  _SortMe := TStringDynArray.Create('abc', 'zwq', 'Long', 'longer');

  TArray.Sort<string>(_SortMe, TDelegatedComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      Result := CompareText(Left, Right);
    end));
end;

Expected result: longer, Long, abc, zwq

1
  • 1
    Where in your code do you compare lengths? Commented Dec 30, 2017 at 10:08

2 Answers 2

5

Adjusting your anonymous function:

function(const Left, Right: string): Integer
    begin
      //Compare by Length, reversed as longest shall come first
      Result := CompareValue(Right.Length, Left.Length);
      if Result = EqualsValue then
        Result := CompareText(Left, Right);
    end));

You'll need to add System.Math and System.SysUtils to your uses.

Sign up to request clarification or add additional context in comments.

Comments

2

I would have used a TStringList for this...

Any way, just customize the comparison function:

  TArray.Sort<string>(_SortMe, TDelegatedComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      Result := length(Right) - length(Left); // compare by decreasing length
      if Result = 0 then
        Result := CompareText(Left, Right);  // compare alphabetically
    end));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.