2

I have a huge list of users and every user has it's id , but it id numbers are messed up so if anyone can show me how can I sort users by numbers , every value has this form

1:Stackoverflow
or
145000:Google 

If I do that manually I think I will lose my mind since tehere are more than 700000 records.Thanks for your time and help....

kludg
  • 26,590
  • 4
  • 63
  • 115
Hijerarhija Uzasa
  • 163
  • 1
  • 2
  • 9
  • see http://stackoverflow.com/questions/5134712/how-to-get-the-sort-order-in-delphi-as-in-windows-explorer – kludg Jun 30 '12 at 15:22

1 Answers1

10

Extract the number like this:

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;

Once you can extract the ID as an integer you can then write a compare function. Like this:

function CompareIDs(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := CompareValue(
    ID(List[Index1]), 
    ID(List[Index2])
  );
end;

CompareValue is an RTL function that returns -1, 0 or 1 depending on the relative values of the two operands.

Feed these building blocks into TStringList.CustomSort and your job is done.

MyStringList.CustomSort(CompareIDs);
David Heffernan
  • 572,264
  • 40
  • 974
  • 1,389