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