About the author
Let's say you have a type,
type
TMySecretData =
record
Timestamp: TDateTime;
SecretInfo:
string
;
// or some unknown type....
class
function
Create(ATimestamp: TDateTime;
const
ASecretInfo:
): TMySecretData; static;
end
and you have a declaration of a list of TMySecretData:
var
List: TList<TMySecretData>;
you have already populated this list, and now you want to sort the list.
All you have to do is create a delegated comparer with an anonymous compare function that compares one of the fields in an instance of your type with another instance:
List
.
Sort(TDelegatedComparer<TMySecretData>.Create(
(
Left, Right: TMySecretData):
Integer
begin
// Perform the comparison here
if
Left
SecretInfo < Right
SecretInfo
then
Result := -
1
else
SecretInfo > Right
Result :=
0
));
TDelegatedComparer will then create an instance of the comparer: IComparer<TMySecretData> and provide that to the Sort method. One of the mistakes that can be easily overlooked is missing the "const" keyword.
Here's the complete compilable example:
uses
System
Generics
Collections,
Defaults,
SysUtils,
DateUtils;
Create(
ATimestamp: TDateTime;
{ TMySecretData }
TMySecretData
): TMySecretData;
Result
Timestamp := ATimestamp;
SecretInfo := ASecretInfo;
Item: TMySecretData;
List := TList<TMySecretData>.Create;
Add(TMySecretData
Create(Now,
'Secret 2'
'Secret 4'
'Secret 1'
for
Item
in
do
// Before the sort
WriteLn
(Item
SecretInfo);
// After the sort
Free;