如何在Delphi XE10中按姓名和出生日期对TObjectList<TPerson>排序?
Delphi XE10中对TObjectList按name和DateOfBirth排序的实现方法
假设我们定义了如下类和对象列表:
TPerson = class private name : String; DateOfBirth: TDatetime; end; // ... aList : TObjectList<TPerson>; // ...
aList已填充以下数据:
| name | DateOfBirth |
|---|---|
| Adam | 01/01/2023 |
| Alice | 01/02/2023 |
| Adam | 01/01/2022 |
需要实现按name升序排序,当name相同时,再按DateOfBirth升序排序,最终得到如下结果:
| name | DateOfBirth |
|---|---|
| Adam | 01/01/2022 |
| Adam | 01/01/2023 |
| Alice | 01/02/2023 |
你当前的代码仅实现了按name排序,未处理同name下的DateOfBirth排序逻辑:
aList.sort(TComparer<TPerson>.Construct( function (const L, R: TPerson): integer begin if L.name=R.name then Result:=0 else if L.name< R.name then Result:=1 else Result:=-1; end));
修改后的实现代码
只需要在name相等的分支里,加入DateOfBirth的比较逻辑即可:
aList.sort(TComparer<TPerson>.Construct( function (const L, R: TPerson): integer begin // 先比较name if L.name < R.name then Result := -1 else if L.name > R.name then Result := 1 else // name相等时,比较DateOfBirth if L.DateOfBirth < R.DateOfBirth then Result := -1 else if L.DateOfBirth > R.DateOfBirth then Result := 1 else Result := 0; end));
逻辑说明
- 优先比较
name:如果L的name小于R的name,返回-1(表示L排在R前面);如果大于则返回1(R排在L前面) - 当
name相等时,转而比较DateOfBirth:逻辑和name比较一致,实现出生日期的升序排列 - 若两者的name和DateOfBirth都完全相同,则返回0,表示排序位置相同
内容的提问来源于stack exchange,提问作者Alelo
相关产品推荐
相关产品推荐

