所以,我希望按长度排序字符串数组(更长的字符串首先排序),如果长度相同,则按字母顺序排序。这是到目前为止:
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;
预期结果:更长,更长,abc,zwq
调整您的匿名功能:
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));
您需要将System.Math和System.SysUtils添加到您的用途中。
我本来会用TStringList
...
无论如何,只需自定义比较功能:
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));