DELPHI7中 TObjectList sort排序问题

网上收集了一点东西

TOBJECTLIST里,有自带的排序功能

TLIST,TSTRINGLIST也有,MS是一样的

SORT里有一个参数: Compare:TListSortCompare

那我们先了解一下 TListSortCompare type

HELP原文:TListSortCompare is the type for callbacks that compare two items in a list.

即 TListSortCompare 是一个比较两个列表项的的回调类型

不知道这么翻译行不行,但意思就是返回一个值来表示LIST中两项的大小

定义:(这个传入的是两项的指针)

type TListSortCompare = function (Item1, Item2: Pointer): Integer;

Value Description

> 0 (positive) Item1 is less than Item2

0 Item1 is equal to Item2

< 0 (negative) Item1 is greater than Item2

于是我们可以定义一个比较函数去定义自己的比较方式

function (Item1, Item2: Pointer): Integer

对于delphi初学者 不懂 item1 和 item2 是什么意思

自己的理解,这是一个对象的指针,就是TOBJECTLIST自己

好比类中套了TOBJECTLIST 那么 怎么来写这个函数呢

网上的高手很厉害,一般不会回答傻问题,可惜我们小白不懂啊!

上代码

function CompareNames(Item1, Item2: Pointer): Integer;

begin

result := Integer(CompareValue(TThingItem(Item1).indexShow,TThingItem(Item2).indexShow));

end;

CompareValue 记得U一下Math

这个函数头一回用 贴上解释吧

7、CompareValue

function CompareValue (const A, B: Extended; Epsilon: Extended = 0): TValueRelationship; overload;

function CompareValue (const A, B: Double; Epsilon: Double = 0): TValueRelationship; overload;

function CompareValue (const A, B: Single; Epsilon: Single = 0): TValueRelationship; overload;

function CompareValue (const A, B: Integer): TValueRelationship; overload;

function CompareValue (const A, B: Int64): TValueRelationship; overload;

uses Math

比较两个值之间的关系

如 A 小于 B 则返回 -1 ,如果相等则为 0 ,如果 A>B 则返回为 1;

好了,上面TThingItem是一个对象,Item1是要表示的TOBJECTLIST,至少我是这么理解的

这里的作用是比较indexshow的大小来达到从小到大的排序!

函数直接添加,无需申明

下面直接调用!排序OK

self.tolWPXM.Sort(@CompareNames);

贴段别人弄好的测试代码开始不懂,后来完全明白是什么了

unitUnit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls, Math;

type

P_MissInfo = ^MissInfo;

MissInfo =record

Missqty:integer;

MissRate:Double;

end;

TForm1 =class(TForm)

Button1: TButton;

procedureButton1Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form1: TForm1;

implementation

{$R*.dfm}

functionCompareNames(Item1, Item2:Pointer):Integer;

begin

result :=Integer(CompareValue(P_MissInfo(Item1).MissRate, P_MissInfo(Item2).MissRate));

end;

procedureTForm1.Button1Click(Sender: TObject);

var

list: Tlist;

PMissInfo: P_MissInfo;

begin

list := Tlist.create;

New(PMissInfo);

PMissInfo.Missqty:=10;

PMissInfo.MissRate:=12.56;

list.Add(PMissInfo);

New(PMissInfo);

PMissInfo.Missqty:=12;

PMissInfo.MissRate:=12.8;

list.Add(PMissInfo);

New(PMissInfo);

PMissInfo.Missqty:=9;

PMissInfo.MissRate:=11.56;

list.Add(PMissInfo);

list.Sort(@CompareNames);

Showmessage(IntToStr(list.Count));

showmessage(FloatToStr(P_MissInfo(list.Items[0]).MissRate));

showmessage(FloatToStr(P_MissInfo(list.Items[1]).MissRate));

showmessage(FloatToStr(P_MissInfo(list.Items[2]).MissRate));

end;

end.