### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook (preview only)

### Author Topic: Sort in generic class  (Read 256 times)

#### mangakissa

• Hero Member
• Posts: 947
##### Sort in generic class
« on: July 23, 2019, 12:31:09 pm »
Regarding to this topic https://forum.lazarus.freepascal.org/index.php/topic,45792.0.html
Code: Pascal  [Select]
1. TMyStringlist = specialize TList<string>;
2. TMyIntegerlist = specialize TList<integer>;
3.
The generic class can hold different types (string, integer, double), but can I also sort the array in the same class without knowing the data type?
Lazarus 1.84 (32b) / FPC 3.0.4
Windows 10

• Hero Member
• Posts: 9278
##### Re: Sort in generic class
« Reply #1 on: July 23, 2019, 12:54:12 pm »
That depends on available standard enumerators or if you have written an enumerator yourself.
For example for strings and ordinals sort should work (given generics.collections) but depending on your type an enumerator might have to be written by you.
I will add a simple example.
Code: Pascal  [Select]
1. {\$mode delphi}{\$warn 5024 off}{\$warn 3124 off}{\$warn 5003 off}
2. uses generics.collections;
3.
4. Type
5.   TMyStringList = TList<string>;
6.   TMyIntegerList = TList<integer>;
7. var
8.   S:TMyStringlist;
9.   L:TMyIntegerList;
10.   ES:string;
11.   EL:Integer;
12. begin
13.   S := TMyStringlist.Create;
14.   try
18.     S.Sort;
19.     For ES in S do
20.       writeln(ES);
21.   finally
22.     S.Free;
23.   end;
24.   L := TMyIntegerList.Create;
25.   try
29.     L.Sort;
30.     For EL in L do
31.       writeln(EL);
32.   finally
33.     L.Free;
34.   end;
35. end.
This only works because there are default enumerators for string and integer.
So it depends on the type if you need to write an enumerator yourself.
« Last Edit: July 23, 2019, 01:07:19 pm by Thaddy »
also related to equus asinus.

#### mangakissa

• Hero Member
• Posts: 947
##### Re: Sort in generic class
« Reply #2 on: July 23, 2019, 02:29:57 pm »
Thaddy, I use fgl and TList<> doesn't have a sort procedure.
Lazarus 1.84 (32b) / FPC 3.0.4
Windows 10