It is necessary to make a program that would sort the list by a specific field. But writing the sorting itself is laziness. Are there any built-in procedures in Delphi?

    1 answer 1

    In Delphi there is a TList which can store arbitrary data types and allows them to be sorted. The TList.Sort() method takes your sorting function as an argument. The list is QuickSort inside TList ( QuickSort used), but each pair of elements is compared by calling the function you specified for this method.

    The minimum example that shows how you can sort a list by a particular field, simply substituting the desired sort function:

     uses Classes, SysUtils; type TListItem = record F1: string; F2: Integer; end; PListItem = ^TListItem; function CompareByF1(Item1, Item2: Pointer): Integer; begin Result := CompareText(PListItem(Item1).F1, PListItem(Item2).F1); end; function CompareByF2(Item1, Item2: Pointer): Integer; begin Result := PListItem(Item1).F2 - PListItem(Item2).F2; end; procedure Test; var I: Integer; VList: TList; VTestItem: PListItem; begin VList := TList.Create; try try // Π·Π°ΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ списка Π΄Π°Π½Π½Ρ‹ΠΌΠΈ for I := 9 downto 0 do begin New(VTestItem); // динамичСскоС Π²Ρ‹Π΄Π΅Π»Π΅Π½ΠΈΠ΅ памяти для элСмСнта списка VTestItem.F1 := 'TestStr#' + IntToStr(I); VTestItem.F2 := I; VList.Add(VTestItem); end; // тСстовая ΠΏΠ΅Ρ€Ρ‡Π°Ρ‚ΡŒ списка Π”Πž сортировки for I := 0 to VList.Count - 1 do begin Writeln(PListItem(VList.Items[I]).F1); end; Writeln; VList.Sort(CompareByF2); // сортировка ΠΏΠΎ Π½ΡƒΠΆΠ½ΠΎΠΌΡƒ Π½Π°ΠΌ полю // тСстовая ΠΏΠ΅Ρ€Ρ‡Π°Ρ‚ΡŒ списка ΠŸΠžΠ‘Π›Π• сортировки for I := 0 to VList.Count - 1 do begin Writeln(PListItem(VList.Items[I]).F1); end; finally for I := 0 to VList.Count - 1 do begin Dispose(VList.Items[I]); // освобоТдСниС Ρ€Π°Π½Π΅Π΅ Π²Ρ‹Π΄Π΅Π»Π΅Π½Π½ΠΎΠΉ памяти end; end; finally VList.Free; end; end; 

    And here: How do I sort a generic list using a custom comparer? There is an example of how to sort the list, in versions of Delphi with generic support.