gpt4 book ai didi

delphi - 如何在通用 TList 中搜索具有特定字段值的记录?

转载 作者:行者123 更新时间:2023-12-03 15:04:16 29 4
gpt4 key购买 nike

关于通用TList的一切。我有这样的结构:

Type
TExtract = record
Wheel: string;
Extract: array [1..5] of Byte;
end;

TExtractList = TList<TExtract>

TEstr = record
Date: TDate;
Extract: TExtractList;
end;

TEstrList = TList<TEstr>;

主要列表是TEXtrList,在这个列表中我有所有日期和日期所有轮子与该日期。我想搜索日期是否存在。如果不存在,我会在 Extract from TEstr 的子列表 TExtractList 中添加信息。当我从 TEstrList 搜索时,Delphi 询问我有关 TEstr 类型的信息。我只需要搜索Date。那么如何在通用 TList 中搜索单个字段?

PS:我已经删除了上一篇文章,因为在这里我试图更好地解释。

最佳答案

我们又来了。

您应该使用内置 TList<T>.BinarySearch()函数,即使它正确地要求 TEstr记录为参数。您首先需要使用TList<T>.Sort()使用与搜索相同的条件对列表进行排序,然后调用 BinarySearch()查找您的记录。

这是一个同时执行这两项操作(排序和搜索)的函数:

uses Generics.Defaults; // this provides TDelegatedComparer
uses Math; // this provides Sign()

function SearchList(Date:TDate; Sort:Boolean; List:TList<TEstr>): Integer;
var Comparer: IComparer<TEstr>;
Dummy: TEstr;
begin
// Prepare a custom comparer that'll be used to sort the list
// based on Date alone, and later to BinarySearch the list using
// date alone.
Comparer := TDelegatedComparer<TEstr>.Construct(
function (const L, R: TEstr): Integer
begin
Result := Sign(L.Date - R.Date);
end
);

// If the list is not sorted, sort it. We don't know if it's sorted or not,
// so we rely on the "Sort" parameter
if Sort then List.Sort(Comparer);

// Prepare a Dummy TEstr record we'll use for searching
Dummy.Date := Date;

// Call BinarySearch() to look up the record based on Date alone
if not List.BinarySearch(Dummy, Result, Comparer) then
Result := -1;
end;

BinarySearch假设列表已排序(这就是二分搜索的本质!)。第一次通话时,您需要设置Sort=True所以列表已正确排序。后续通话 Sort应该是False 。当然,在实际使用中,您可能有单独的搜索和排序例程,并且您可能将它们作为从 TList<TEstr> 降序的类的方法。 (让事情变得更容易)。为了节省开支,我将两者放在同一个例程中。

关于delphi - 如何在通用 TList 中搜索具有特定字段值的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8051327/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com