Delphi-通用TList排序

我正在使用 Generics.Collections.TList 和 Sort 方法。它工作正常,但我想最后对空值或空值进行排序。按升序和降序排序。如何实施?

这是我的排序功能:

function TForm.SortByColumn(ColumnID: integer; SortDirRev: integer):boolean;
var
  Comparison: TComparison<TSymData>;
begin
  Result := false;

  Comparison := nil;

  if ColumnID = 0 then
    begin
      Comparison := function(const Left, Right: TSymData): integer
      begin
        Result := SortDirRev * TComparer<string>.Default.Compare(Left.Name,Right.Name);
      end;
    end
  else
    begin
      Comparison := function(const Left, Right: TSymData): integer
      begin
        Result := SortDirRev * TComparer<string>.Default.Compare(Left.Sub[ColumnID-1],Right.Sub[ColumnID-1]);
      end;
    end;

  if assigned(Comparison) then
    FSymList.Sort(TComparer<TSymData>.Construct(Comparison));

end;

回答

您只需要提供一个考虑空值的比较函数。

比较函数是一个函数,它接受两个项目 A 和 B,如果 A 应该在 B 之前,则返回 -1,如果 A 应该在 B 之后,则返回 +1,如果 A 和 B 被认为相等,则返回 0。

例如,要L使用标准字符串比较器对字符串列表进行排序,您可以这样做(仅供参考)

L.Sort(
  TComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      Result := CompareStr(Left, Right)
    end
  )
);

要根据字符串长度排序,请执行

L.Sort(
  TComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      Result := CompareValue(Left.Length, Right.Length)
    end
  )
);

现在,如果你想对字符串进行正常排序,除了你明确要求所有空字符串先行,你可以这样做

L.Sort(
  TComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      if Left.IsEmpty and not Right.IsEmpty then
        Result := -1
      else if not Left.IsEmpty and Right.IsEmpty then
        Result := +1
      else
        Result := CompareStr(Left, Right)
    end
  )
);

要让空字符串最后,请执行

L.Sort(
  TComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      if Left.IsEmpty and not Right.IsEmpty then
        Result := +1
      else if not Left.IsEmpty and Right.IsEmpty then
        Result := -1
      else
        Result := CompareStr(Left, Right)
    end
  )
);


以上是Delphi-通用TList排序的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>