Delphi - 使用混合值对TStringList进行排序 - 整数和字符串

时间:2017-12-18 16:12:58

标签: sorting delphi

我对使用混合值排序TStringList有一点问题。它类似于:

  

7567533575乔
  1543779744 Ann
  9757462323杰克   6999966578 Stef

我需要对此列表进行排序以查看:

  

1543779744 Ann
  6999966578 Stef
  7567533575乔
  9757462323杰克

我可以使用大约3x for循环,使用字符串修剪和一个数组来完成此操作。但这是非常蹩脚的解决方案...我想,有人有最好的代码。我不懂CustomSort ......呃。求你帮帮我。

  • 我使用的是Delphi 10。

1 个答案:

答案 0 :(得分:5)

使用CustomSort()是正确的解决方案。只需传递一个解析和比较2个输入字符串的函数,返回:

  • <如果第一个字符串应出现在第二个字符串之前,则为0。

  • 0如果2个字符串“相等”且任何一个字符串可以出现在另一个字符串之前。

  • >如果第二个字符串应出现在第一个字符串之前,则为0。

function MySortFunc(List: TStringList; Index1, Index2: Integer): Integer;
var
  Value1, Value2: Int64;
  S: string;
begin
  S := List[Index1];
  Value1 := StrToInt64(Copy(S, 1, Pos(' ', S)-1));
  S := List[Index2];
  Value2 := StrToInt64(Copy(S, 1, Pos(' ', S)-1));
  if Value1 < Value2 then
    Result := -1
  else if Value2 < Value1 then
    Result := 1
  else
    Result := 0;
end;

MyStringList.CustomSort(MySortFunc);