我有一个巨大的用户列表,每个用户都有它的ID,但是它的ID数字搞砸了,所以如果有人可以告诉我如何按数字对用户进行排序,每个值都有这种形式
1:Stackoverflow
or
145000:Google
如果我手动这样做,我想我会失去理智,因为有超过700000条记录。谢谢你的时间和帮助....
答案 0 :(得分:10)
像这样提取数字:
function ID(const str: string): Integer;
var
p: Integer;
begin
p := Pos(':', str);
if p=0 then
raise Exception.CreateFmt('Invalid string format: %s', [str]);
Result := StrToInt(Copy(str, 1, p-1));
end;
一旦您可以将ID提取为整数,您就可以编写比较函数。像这样:
function CompareIDs(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := CompareValue(
ID(List[Index1]),
ID(List[Index2])
);
end;
CompareValue
是一个RTL函数,它返回-1,0或1,具体取决于两个操作数的相对值。
将这些构建块导入TStringList.CustomSort
,您的工作就完成了。
MyStringList.CustomSort(CompareIDs);