I have a number of Typed TLists which I am having problems getting to sort
Normally, for an untyped TList, I would have a function such as:
function SortByJob(Item1: Pointer; Item2: Pointer): Integer;
var
p1, p2: JobPointer;
begin
p1 := JobPointer(Item1);
p2 := JobPointer(Item2);
if p1.job > p2.job then
Result := 1
else
if p1.job = p2.job then
Result := 0
else
Result := -1
end;
Which would be called by the list
JobList.Sort(SortByJob)
However I have decided in my current application that we want to lock the TLists to certain pointer types, so in the above example we would have the JobList declared as:
JobList: array[0..4] of TList<JobsPointer>;
Now when I call
JobList[0].Sort(SortByJob)
I get a "not enough parameters" error.
Any ideas?
I have compared that if I use the Sort function above on an untyped "standard" TList then it will compile correctly...
A generic list is sorted using a instance of IComparer. Here is an example that sorts a list of integers:
uses Generics.Collections, Generics.Defaults;
procedure TForm1.FormCreate(Sender: TObject);
var
L : TList<integer>;
begin
L := TList<integer>.Create;
L.Add(2);
L.Add(1);
L.Sort(TComparer<integer>.Construct(
function (const L, R: integer): integer
begin
Result := L - R;
end
)) ;
L.Free;
end;