[SOLVED] Is there a way to sort a TLisistBox desc? lazarus / 21-General ---------------------------------------------------------------------- Hansvb · 2023-06-24 07:35 Hi, Is there a way to sort a TLisistBox desc? Sort seems always Asc. And if you Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Sorted := False; then the listbox items will not go back to the original order. ---------------------------------------------------------------------- TRon · 2023-06-24 08:20 Quote from: Hansvb on June 24, 2023, 09:35:51 amIs there a way to sort a TLisistBox desc? No and yes. The listbox itself does not have such proficiency but you can make it so that your items are sorted the way you want them to. As Remy Lebeau once wrote: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function CompareDates(List: TStringList; Index1, Index2: Integer): Integer;var  d1, d2: TDateTime;begin   d1 := StrToDate(List[Index1]);   d2 := StrToDate(List[Index2]);   if d1 < d2 then     Result := -1   else if d1 > d2 then      Result := 1   else     Result := 0;end; procedure TForm1.Button1Click(Sender: TObject);var  sl: TStringList;begin  sl := TStringList.Create;   try         sl.Assign(ListBox1.Items);    sl.CustomSort(CompareDates);    ListBox1.Items.Assign(sl);  finally  sl.Free  end;end; The only thing left is to come up with an descending sorting algorithm  QuoteAnd if you Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Sorted := False; then the listbox items will not go back to the original order. Which component does support that by default ? You would have to make use of an index-file in order to accomplish that. ---------------------------------------------------------------------- cdbc · 2023-06-24 08:27 Hi Alas, just checked, "CustomSort(aCompare: TStringListSortCompare)" is first introduced in TStringList. As "Items" of a listbox is TStrings, then I thought you could take that route  :'( ...And TListbox.Sorted just defers the work to the underlying widgetset  Maybe SendMessage ?!? Edit: TRon beat me to it, I kinda like Remy Lebeau's solution  Regards Benny ---------------------------------------------------------------------- TRon · 2023-06-24 08:38 Better would have been if the virtual listbox style was supported/implemented but alas QuotelbVirtual  Not used in the current LCL version. You could probably achieve something similar to virtual with custom drawn, using an index array (sorry, because I wrongly mentioned file before) that stores the sorted index (additional with the addition of the original order). In that regards, Remy's solution is (indeed) more likeable. hint to Hans: you can store the original order that way as well. It is just very inefficient when there are many items in the list. ---------------------------------------------------------------------- Nicole · 2023-06-24 15:49 Here is a code snippet of custom sort for a SL = StringList you can adjust it for your needs Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TStringList.CustomSort(CompareFn: TStringListSortCompare); begin  If (FCount>1) and (FForceSort or (FSortStyle<>sslAuto))  then    begin  Changing;    QuickSort(0,FCount-1, CompareFn);    Changed;    end;end; call it by Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i SL_Range.CustomSort(@StringListSortComparefn2); It is important, not to use this within a class. And all in all: This was a code from an old source. Would I do it new, I would prefer to sort in a different way, because writing and debugging seems rather complex to me. ---------------------------------------------------------------------- jamie · 2023-06-24 17:47 On windows, you can set the ListBox class with a LBS_SORT, in which case it will sort as new entries come in. Also, if the Listbox has a ownerdraw set on it, which for the LCL may be already in the background, and you will receive a WM_COMPAREITEM message with the list box ID with the two strings, the new one and one being compared to. ---------------------------------------------------------------------- Hansvb · 2023-06-24 18:31 I found the Comparedates example too when i googled. But i can't get that example to work, the line Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i sl.CustomSort(CompareDates); goes wrong. I do no not know what index1 and index2 must be. ---------------------------------------------------------------------- TRon · 2023-06-25 02:42 Quote from: Hansvb on June 24, 2023, 08:31:09 pmI found the Comparedates example too when i googled. But i can't get that example to work, the line Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i sl.CustomSort(CompareDates); goes wrong. I do no not know what index1 and index2 must be. It is a difference between Delphi and Free Pascal that whenever a function/procedure expects a pointer to a procedure or function that FPC requires that to be prefixed with a @ character (to distinct between an actual invocation or (only) passing the pointer). An example of what you are trying to accomplish: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit Unit1; {$mode objfpc}{$H+} interface uses  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls; type   { TForm1 }   TForm1 = class(TForm)    ListBox1: TListBox;    RadioGroup1: TRadioGroup;    procedure FormCreate(Sender: TObject);    procedure FormDestroy(Sender: TObject);    procedure RadioGroup1Click(Sender: TObject);  private    ListItems: TStringList;  public   end; var  Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure ShuffleStrings(Strings: TStrings);var  i: Integer;begin  for i := Pred(Strings.Count) downto 1    do Strings.Exchange(i, Random(Succ(i)))end; function CompareAscending(List: TStringList; Index1, Index2: Integer): Integer;begin  result := CompareStr(List[Index1], List[Index2])end; function CompareDescending(List: TStringList; Index1, Index2: Integer): Integer;begin  result := CompareStr(List[Index1], List[Index2]) * -1end; procedure TForm1.FormCreate(Sender: TObject);const  SomeItems : TStringArray =   ('One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten');begin  RadioGroup1.Items.Add('Unsorted (None)');  RadioGroup1.Items.Add('Ascending');  RadioGroup1.Items.Add('Descending');   ListItems := TStringList.Create;  ListItems.AddStrings(SomeItems);  ShuffleStrings(ListItems);   RadioGroup1.ItemIndex := 0end; procedure TForm1.FormDestroy(Sender: TObject);begin  ListItems.Freeend; procedure TForm1.RadioGroup1Click(Sender: TObject);var  sl: TStringList;  index: integer;begin  index:= (Sender as TRadioGroup).ItemIndex;  sl:= TStringList.Create;   if (Index<0) or (Index>2)    then exit;   if index=0   then sl.Assign(ListItems)    else sl.Assign(ListBox1.Items);   if index=1   then sl.CustomSort(@CompareAscending)  else if index=2   then sl.CustomSort(@CompareDescending);   ListBox1.Items.Assign(sl);   sl.free;end; end. ---------------------------------------------------------------------- Hansvb · 2023-06-27 14:25 At first i got the same error but now i see it. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function CompareAscending(List: TStringList; Index1, Index2: Integer): Integer;  i tried (wrong way): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TFrmMain.CompareAscending(List: TStringList; Index1, Index2: Integer): Integer;  Without the Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i TFrmMain. it works. Until now i never used a function like that. Thanks a lot. ---------------------------------------------------------------------- Nicole · 2023-06-27 15:33 Thank you for posting. This is the same what I said above about CustomSort, "it must not be part of a class". ---------------------------------------------------------------------- Hansvb · 2023-06-27 19:08 Can i see these functions ouside of a class as an extention method as c# has? ---------------------------------------------------------------------- TRon · 2023-06-27 20:26 Quote from: Hansvb on June 27, 2023, 09:08:42 pmCan i see these functions ouside of a class as an extention method as c# has? Not really. If anything like that then it would be what Pascal refers to as a class helper. A class helper (but also type helper) allows you to add new methods to existing classes/types. With regards to the sorting it is just a method (customsort) that is already part of the class. The customsort method itself already has the sorting algorithm 'included' but lacks a detail (on purpose so it can be adjusted) to compare two value against each other (*). The customsort method of the class "dictates" (it is simply implemented that way) to provide the comparison routine. (*) although I wrote two values you can actually make multiple checks, for instance to see if a text ends with a number and then do a alphanumeric sort. or as in the example from Remy interpret the text as being dates. ---------------------------------------------------------------------- Nicole · 2023-06-28 09:17 About C# I do not know enough. Here are 2 snippets about this topic, I found in my memos. Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i                When you are working with a TList object and want to sort the (list) items based on a custom criteria, you can use the next code... The following example code sorts the items in a list in alphabetical order based on their names. It assumes that the list contains only references to variables of type TMyListItem, where TMyListItem is defined as: type  TMyListItem = record    Points : Integer;    Name: string[255] ;  end; The CompareNames function performs the comparisons between objects in the list. The list is sorted when the user clicks a button. ~~~~~~~~~~~~~~~~~~~~~~~~~function CompareNames(Item1, Item2: Pointer): Integer;begin   Result := CompareText((Item1 as TMyListItem).Name,                         (Item2 as TMyListItem).Name) ;end; procedure TForm1.Button1Click(Sender: TObject) ;begin   List1.Sort(@CompareNames) ;end; {Note: the Sort method needs a pointer toa custom function (with the signature below)that indicates how the items are to be ordered. type   TListSortCompare = function (Item1,                                Item2: Pointer): Integer; Your sorting / comparison function should returna positive value if Item1 is less than Item2,0 if they are equal, and a negative valueif Item1 is greater than Item2.} The translation of the German text below reads: Never put those function in classes, because they are functions and must not be methods. The function-call is passed on to the unit "classes" internally Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i // 2 Funktionen, um das die StringLists der Korrelationen zu sortieren.// dürfen NICHT TmyKlasse. ... sein, weil das eine Methode wäre!// Aufruf intern: StringList.CustomSort zeigt auf diese beiden Funktionen, die via Aufruf an die interne Unit "classes" übergeben werdenfunction StringListSortComparefn(List: TStringList; Index1, Index2: Integer): Integer;var  i: Integer;     s:string;     d1, d2: double; begin // in List werden die gegeneinander zu sortierenden Zeilen übergeben  result:=0;  If (List[Index1] = '') or (List[Index2] = '') then exit;   i:=0;  i:=AnsiPos('%',List[Index1]);  // '0,6% Korrelation zwischen BO und SF'  if i < 1 then exit; // bei Null wird es nicht gefunden, bei 1 steht % ohne Zahl da  s:=LeftStr(List[Index1],i-1);  // sortiert die Korr der Höhe nach  d1:=StrToFloat(s);  d1:=Abs(d1);   i:=AnsiPos('%',List[Index2]);  s:=LeftStr(List[Index2],i-1);  d2:=StrToFloat(s);  d2:=Abs(d2);   if d1 = d2 then result:=0;      // beide Einträge haben die gleiche Sortier-Reihenfolge  if d1 > d2 then result:= 1;   // Sortierreihenfolge, allenfalls +/- vertauschen  if d1 < d2 then result:= -1;end;// s.oberhalt und: sortiert die absoluten Werte der Korrelationen, also -97 vor +28function StringListSortComparefn2(List: TStringList; Index1, Index2: Integer): Integer;var  i: Integer;     s:string;     d1, d2: double;     gueltig: Boolean; begin // in List werden die gegeneinander zu sortierenden Zeilen übergeben   result:=0;  d1:=0; d2:=0;  If (List[Index1] = '') or (List[Index2] = '') then exit;   i:=0;   s:=List[Index1];  i:=AnsiPos(':',s);  // 'AD Korrelation zu BO: -15,3%'  if (i < 1) then exit; // bei Null wird es nicht gefunden  s:=copy(s, i+1,Length(s));  s:=Trim(s);  s:=copy(s, 0, Length(s) -1);  Trim(s);  gueltig:=TryStrToFloat(s,d1);  if gueltig=false then exit; // absichtlich keine Fehlermeldung, können zuviele werden!  d1:=Abs(d1);   s:=List[Index2];  i:=AnsiPos(':',s);  // 'AD Korrelation zu BO: -15,3%'  if (i < 1) then exit; // bei Null wird es nicht gefunden  s:=copy(s, i+1,Length(s));  s:=Trim(s);  s:=copy(s, 0, Length(s) -1);  Trim(s);  gueltig:=TryStrToFloat(s,d2);  if gueltig=false then exit; // absichtlich keine Fehlermeldung, können zuviele werden!  d2:=Abs(d2);   if d1=d2 then result:=0;      // beide Einträge haben die gleiche Sortier-Reihenfolge  if d1 > d2 then result:= 1;   // Sortierreihenfolge, allenfalls +/- vertauschen  if d1 < d2 then result:= -1; end; ---------------------------------------------------------------------- Thaddy · 2023-06-28 10:14 QuoteNever put those function in classes, because they are functions and must not be methods.You CAN put those in classes, provided they are declared as class methods and decorated with static. That has the same signature as regular routines, because there is no hidden self. E.G:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc}type TSomeClass=class public // has the same signature as a normal procedure class procedure test;static; end; class procedure TSomeClass.test;static; begin   writeln('test'); end;  begin   TSomeClass.Test; end. ---------------------------------------------------------------------- Nicole · 2023-06-28 10:33 You used two words, I have read very often, but had never understood. "static" and "class methods" The function "Refactor" gave me messages with it, I was clueless with. The occasion when I read them, is when I wanted to migrate methods from one unit to the other, because of better-systematic. Usually I copied them by hand or left them as there are. My posting in short: Are there anywhere easy-to-understand links which explain "class methods" and "static"? and "class helper" is one more. ---------------------------------------------------------------------- ravida · 2023-06-28 11:57 No, the TListBox component in Delphi does not have a built-in way to sort its elements in descending order. By default, it sorts the elements in ascending order. If you want to display the elements in descending order, you have to sort the elements manually before populating the TListBox. Here is a general approach you can take: Create a TStringList object. Paste all the items from the TListBox into the TStringList. Use the CustomSort method of the TStringList and provide a custom comparison function that sorts the items in descending order. Delete the TListBox. Put the sorted elements from the TStringList back into the TListBox. Here is a sample code snippet: var   ListBoxItems: TStringList;   I: Integer; begin   ListBoxItems := TStringList.Create;   try     // Add items from TListBox to TStringList     ListBoxItems.Assign(ListBox1.Items);     // Custom sort in descending order     ListBoxItems.CustomSort(       function(const S1, S2: string): Integer       begin         Result := -CompareStr(S1, S2);       end     );     // Clear the TListBox     ListBox1.Clear;     // Add sorted items back to TListBox     for I := 0 to ListBoxItems.Count - 1 do       ListBox1.Items.Add(ListBoxItems);   finally     ListBoxItems.Free;   end; end; Note that this procedure assumes that you are using the VCL framework in Delphi. If you are using a different framework or a third-party component, the specific steps and code may differ. thanks and regards pawan tanwar ---------------------------------------------------------------------- TRon · 2023-06-28 12:07 Quote from: Nicole on June 28, 2023, 12:33:22 pmMy posting in short: Are there anywhere easy-to-understand links which explain "class methods" and "static"? and "class helper" is one more. I'm sure you already came across the links I post but I do believe they are written in an understandable manner ? - class methods - static class methods - and though not authoritative (because wiki) but very easy to read: class helpers (or actually helpers in general). @ravida: Yeah introduce anonymous functions, a perfect idea to let people install trunk when you consider the question(s). ---------------------------------------------------------------------- Thaddy · 2023-06-28 12:54 Listbox items are of type TStrings, so you can call reverse on it and make a copy, like so: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc}{$H+}uses classes;const sa:array of string = ('a','b','c');var L1,L2:Tstrings;begin   L1:=TStringlist.Create;   L2:=TStringlist.Create;   try     L1.Addstrings(sa); // This can be a TListbox.Items     L1.Reverse(L2); // target is L2     writeln(L2.Text);// inverse of L1, assign this to TListBox.Items   finally     L1.Free;     L2.free;   end;  end.Subsequently assign the new Tstrings (L2) to the list box. Nothing fancy. Although there are two caveats: if you call the reverse procedure on itself, the reversed list will be added, so you need to have a separate TStrings instance, use the procedure reverse to contain the reversed order, and the assign it!. The reverse function leaks memory, but the reverse procedure does not leak. I will report a bug for the function. More info: https://www.freepascal.org/docs- html/rtl/classes/tstrings.reverse.html