I’m kinda a Delphi-newbie and I don’t get how the Sort method of a TList of Records is called in order to sort the records by ascending integer value.
I have a record like the following:
type
TMyRecord = record
str1: string;
str2: string;
intVal: integer;
end;
And a generic list of such records:
TListMyRecord = TList<TMyRecord>;
Have tried to find a code-example in the help files and found this one:
MyList.Sort(@CompareNames);
Which I can’t use, since it uses classes. So I tried to write my own compare function with a little different parameters:
function CompareIntVal(i1, i2: TMyRecord): Integer;
begin
Result := i1.intVal - i2.intVal;
end;
But the compiler always throws a ‘not enough parameters’ – error when I call it with open.Sort(CompareIntVal);, which seems obvious; so I tried to stay closer to the help file:
function SortKB(Item1, Item2: Pointer): Integer;
begin
Result:=PMyRecord(Item1)^.intVal - PMyRecord(Item2)^.intVal;
end;
with PMyRecord as PMyRecord = ^TMyRecord;
I have tried different ways of calling a function, always getting some error…
The
Sortoverload you should be using is this one:Now, you can create an
IComparer<TMyRecord>by callingTComparer<TMyRecord>.Construct. Like this:I’ve written the
Comparisonfunction as an anonymous method, but you could also use a plain old style non-OOP function, or a method of an object.One potential problem with your comparison function is that you may suffer from integer overflow. So you could instead use the default integer comparer.
It might be expensive to call
TComparer<Integer>.Defaultrepeatedly so you could store it away in a global variable:Another option to consider is to pass in the comparer when you create the list. If you only ever sort the list using this ordering then that’s more convenient.
And then you can sort the list with