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
期望结果:长,长,abc, zwq。
2 个解决方案
#1
4
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.
您需要添加系统。数学和系统。SysUtils使用。
#2
1
I would have used a TStringList
for this...
我会用一个TStringList…
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));
#1
4
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.
您需要添加系统。数学和系统。SysUtils使用。
#2
1
I would have used a TStringList
for this...
我会用一个TStringList…
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));