自定义将Delphi TStringList名称/值对排序为整数

Jak*_*ays 4 delphi sorting

我有一个名称/值对的TStringList.这些名称都是9个整数值,当然是字符串),值都是字符串(以逗号分隔).

例如

5016=Catch the Fish!,honeyman,0
30686=Ozarktree1 Goes to town,ozarktreel,0
Run Code Online (Sandbox Code Playgroud)

...

我想调用add例程并在TStringlist中添加新行,但之后需要一种方法对列表进行排序.

例如

Tags.Add(frmTag.edtTagNo.Text + '=' +
         frmTag.edtTitle.Text + ',' +
         frmTag.edtCreator.Text + ',' +
         IntToStr(ord(frmTag.cbxOwned.Checked)));
Tags.Sort;
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的:

Tags:= TStringList.Create;
 Tags.CustomSort(StringListSortComparefn);
 Tags.Sorted:= True;
Run Code Online (Sandbox Code Playgroud)

我的自定义排序例程:

function StringListSortComparefn(List: TStringList; Index1, Index2: Integer): Integer;
var
 i1, i2 : Integer;
begin
 i1 := StrToIntDef(List.Names[Index1], 0);
 i2 := StrToIntDef(List.Names[Index2], 0);
 Result:= CompareValue(i1, i2);
end;
Run Code Online (Sandbox Code Playgroud)

但是,它似乎仍然像字符串而不是整数一样对它们进行排序.

我甚至尝试创建自己的类:

type
 TXStringList = class(TStringList)
 procedure Sort;override;
end;

implementation

function StringListSortComparefn(List: TStringList; Index1, Index2: Integer): Integer;
var
i1, i2 : Integer;
begin
i1 := StrToIntDef(List.Names[Index1], 0);
i2 := StrToIntDef(List.Names[Index2], 0);
Result:= CompareValue(i1, i2);
end;

procedure TXStringList.Sort;
begin
 CustomSort(StringListSortComparefn);
end;
Run Code Online (Sandbox Code Playgroud)

我甚至在SO上尝试了一些例子(例如,将TSTringList Names属性排序为整数而不是字符串)

有人能告诉我我做错了什么吗?每次,列表都按字符串排序,而不是整数.

30686=Ozarktree1 Goes to town,ozarktreel,0
5016=Catch the Fish!,honeyman,0
Run Code Online (Sandbox Code Playgroud)

Ken*_*ite 6

你可以做一个简单的整数减法:

function StringListSortComparefn(List: TStringList; Index1, Index2: Integer): Integer;
var
 i1, i2 : Integer;
begin
 i1 := StrToIntDef(List.Names[Index1], 0);
 i2 := StrToIntDef(List.Names[Index2], 0);
 Result := i1 - i2
end;
Run Code Online (Sandbox Code Playgroud)

要反转排序顺序,只需在减法中反转操作数:

Result := i2 - i1;
Run Code Online (Sandbox Code Playgroud)

这是一个快速,可编译的控制台示例:

program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

function StringListSortProc(List: TStringList; Index1, Index2: Integer): Integer;
var
  i1, i2: Integer;
begin
  i1 := StrToIntDef(List.Names[Index1], -1);
  i2 := StrToIntDef(List.Names[Index2], -1);
  Result := i1 - i2;
end;

var
  SL: TStringList;
  s: string;
begin
  SL := TStringList.Create;
  SL.Add('3456=Line 1');
  SL.Add('345=Line 2');
  SL.Add('123=Line 3');
  SL.Add('59231=Line 4');
  SL.Add('545=Line 5');
  WriteLn('Before sort');
  for s in SL do
    WriteLn(#32#32 + s);
  SL.CustomSort(StringListSortProc);
  WriteLn('');
  WriteLn('After sort');
  for s in SL do
    WriteLn(#32#32 + s);
  ReadLn;
  SL.Free;
end.
Run Code Online (Sandbox Code Playgroud)

结果输出:

Before sort
  3456=Line 1
  345=Line 2
  123=Line 3
  59231=Line 4
  545=Line 5

After sort
  123=Line 3
  345=Line 2
  545=Line 5
  3456=Line 1
  59231=Line 4
Run Code Online (Sandbox Code Playgroud)