You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Delphi XE10中按姓名和出生日期对TObjectList<TPerson>排序?

Delphi XE10中对TObjectList按name和DateOfBirth排序的实现方法

假设我们定义了如下类和对象列表:

TPerson = class
private 
    name : String;
    DateOfBirth: TDatetime;
end;

// ...

aList : TObjectList<TPerson>;

// ...

aList已填充以下数据:

nameDateOfBirth
Adam01/01/2023
Alice01/02/2023
Adam01/01/2022

需要实现按name升序排序,当name相同时,再按DateOfBirth升序排序,最终得到如下结果:

nameDateOfBirth
Adam01/01/2022
Adam01/01/2023
Alice01/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));

逻辑说明

  1. 优先比较name:如果L的name小于R的name,返回-1(表示L排在R前面);如果大于则返回1(R排在L前面)
  2. 当name相等时,转而比较DateOfBirth:逻辑和name比较一致,实现出生日期的升序排列
  3. 若两者的name和DateOfBirth都完全相同,则返回0,表示排序位置相同

内容的提问来源于stack exchange,提问作者Alelo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:20:25