Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list by first number?

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....

like image 313
Hijerarhija Uzasa Avatar asked Nov 29 '25 04:11

Hijerarhija Uzasa


1 Answers

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);
like image 178
David Heffernan Avatar answered Dec 02 '25 05:12

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!