How to make an Excel-Like Sort By A, Then By B in a TObjectList<> using multiple comparers

前端 未结 3 1088
离开以前
离开以前 2021-02-01 20:23

I have just started to use generics, and I am currently having a problem doing sorting on multiple fields.

Case:
I have a PeopleList as a TObjectList

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 20:54

    Put your sort criteria in a list that includes the direction to sort and the function to use to compare items. A record like this could help:

    type
      TSortCriterion = record
        Ascending: Boolean;
        Comparer: IComparer;
      end;
    

    As the user configures the desired ordering, populate the list with instances of that record.

    var
      SortCriteria: TList;
    

    The Comparer member will refer to the functions you've already written for comparing based on name and age. Now write a single comparison function that refers to that list. Something like this:

    function Compare(const A, B: TPerson): Integer;
    var
      Criterion: TSortCriterion;
    begin
      for Criterion in SortCriteria do begin
        Result := Criterion.Comparer.Compare(A, B);
        if not Criterion.Ascending then
          Result := -Result;
        if Result <> 0 then
          Exit;
      end;
    end;
    

提交回复
热议问题