我创建了一个包含名称/值对的TStringList
,我想根据其值对TStringList
进行排序,然后将具有最大值的名称分配给Labels。
SL: TStringList;
SL:= TStringList.Create;
SL.Values['chelsea']:= '5';
SL.Values['Liverpool']:= '15';
SL.Values['Mancity']:= '10';
SL.Values['Tot']:= '0';
SL.Values['Manunited']:= '20';
最后,此TStringList
必须按值分类。实际上,名字必须是具有最高价值的名字。
您可以使用CustomSort
方法执行此操作。像这样:
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
function StringListSortProc(List: TStringList; Index1, Index2: Integer): Integer;
var
i1, i2: Integer;
begin
i1 := StrToInt(List.ValueFromIndex[Index1]);
i2 := StrToInt(List.ValueFromIndex[Index2]);
Result := i2 - i1;
end;
var
SL: TStringList;
Index: Integer;
begin
SL := TStringList.Create;
try
SL.Values['Chelsea'] := '5';
SL.Values['Liverpool'] := '15';
SL.Values['Man City'] := '10';
SL.Values['Spurs'] := '0';
SL.Values['Man United'] := '20';
WriteLn('Before sort');
for Index := 0 to SL.Count-1 do
WriteLn(' ' + SL[Index]);
SL.CustomSort(StringListSortProc);
WriteLn;
WriteLn('After sort');
for Index := 0 to SL.Count-1 do
WriteLn(' ' + SL[Index]);
finally
SL.Free;
end;
ReadLn;
end.
我不记得何时添加ValueFromIndex
方法。如果它在Delphi 7中不存在,则可以这样模拟:
function ValueFromIndex(List: TStringList; Index: Integer): string;
var
Item: string;
begin
Item := List[Index];
Result := Copy(Item, Pos('=', Item) + 1, MaxInt);
end;
function StringListSortProc(List: TStringList; Index1, Index2: Integer): Integer;
var
i1, i2: Integer;
begin
i1 := StrToInt(ValueFromIndex(List, Index1));
i2 := StrToInt(ValueFromIndex(List, Index2));
Result := i2 - i1;
end;
程序输出:
排序之前切尔西= 5利物浦= 15曼城= 10马刺= 0曼联= 20经过排序曼联= 20利物浦= 15曼城= 10切尔西= 5马刺= 0