本文整理自网络,侵删。
默认排序比较类您可以使用TArray.Sort对数组进行排序。
对数字数组进行排序的示例uses System.Generics.Collections, System.Generics.Defaults;var Values: array[0..8] of Integer = (1,3,5,7,9,8,6,2,4); I: Integer;begin TArray.Sort<Integer>(Values); for I in Values do Write(I);end.执行结果
123456789字符串数组排序示例uses System.Generics.Collections, System.Generics.Defaults;var Values: array[0..3] of string = ('Carol', 'Bob', 'Alice', 'Dave'); S: string;begin TArray.Sort<string>(Values); for S in Values do WriteLn(S);end.执行结果
AliceBobCarolDave通过在继承自IComparer的类中指定比较方法来进行排序通过将继承IComparer的类指定为TArray.Sort的第二个参数,可以在任何条件下对数组进行排序。
记录用于示例代码。
type TMyRecord = record I: Integer; S: string; end;按TMYRECORD的I字段递增顺序排序的示例比较类,以降序对TMyRecord的I字段进行排序
type TMyRecordComparer1 = class(TComparer<TMyRecord>) public function Compare(const Left, Right: TMyRecord): Integer; override; end;
function TMyRecordComparer1.Compare(const Left, Right: TMyRecord): Integer;begin Result := (Right.I - Left.I);end;样例程序
var Values: array[0..3] of TMyRecord = ( (I: 1; S: 'Carol'), (I: 3; S: 'Bob'), (I: 4; S: 'Alice'), (I: 2; S: 'Dave') ); R: TMyRecord;
begin TArray.Sort<TMyRecord>(Values, TMyRecordComparer1.Create); for R in Values do WriteLn(Format('%d:%s', [R.I, R.S]));end.执行结果
4:Alice3:Bob2:Dave1:CarolTMYRECORD的S字段的升序排序示例比较类,该类按升序对TMyRecord的S字段进行排序
type TMyRecordComparer2 = class(TComparer<TMyRecord>) public function Compare(const Left, Right: TMyRecord): Integer; override; end;
function TMyRecordComparer2.Compare(const Left, Right: TMyRecord): Integer;begin Result := System.SysUtils.CompareStr(Left.S, Right.S);end;样例程序
var Values: array[0..3] of TMyRecord = ( (I: 1; S: 'Carol'), (I: 3; S: 'Bob'), (I: 4; S: 'Alice'), (I: 2; S: 'Dave') ); R: TMyRecord;
begin TArray.Sort<TMyRecord>(Values, TMyRecordComparer2.Create); for R in Values do WriteLn(Format('%d:%s', [R.I, R.S]));end.执行结果
4:Alice3:Bob1:Carol2:Dave通过委托给回调例程对比较进行排序System.Generics.Defaults.TDelegatedComparer类将比较过程委托给回调例程。
TMYRECORD的S字段的升序排序示例var Values: array[0..3] of TMyRecord = ( (I: 1; S: 'Carol'), (I: 3; S: 'Bob'), (I: 4; S: 'Alice'), (I: 2; S: 'Dave') ); R: TMyRecord;
begin TArray.Sort<TMyRecord>(Values, TDelegatedComparer<TMyRecord>.Construct( function(const Left, Right: TMyRecord): Integer begin Result := System.SysUtils.CompareStr(Left.S, Right.S); end )); for R in Values do WriteLn(Format('%d:%s', [R.I, R.S]));end.执行结果
4:Alice3:Bob1:Carol2:Dave
相关阅读 >>
Delphi winapi: getclassname - 获取指定窗口的类名
Delphi xe 10.2.1 fmx平台 在图片上写字方法
Delphi lastdelimiter:在字符串中查找选定的字符最后出现的位置
更多相关阅读请进入《Delphi》频道 >>