我在修改 GENERIC SEARCH 的解决方案时遇到了麻烦 因为我的类(class)比较复杂,我需要创建几个不同的搜索函数
procedure TForm1.Button1Click(Sender: TObject);
var
activities: TList<TActivityCategory>;
search: TActivityCategory;
begin
activities := TObjectList<TActivityCategory>.Create(
TDelegatedComparer<TActivityCategory>.Create(
function(const Left, Right: TActivityCategory): Integer
begin
Result := CompareText(Left.Name, Right.Name);
end));
.....
假设我的 TActivityCategory 看起来像
TActivityCategory = class
FirstName : String;
Secondname : String;
onemore .....
end;
如何在我的事件类中实现对每个字符串的搜索?
最佳答案
在您的位置,我会编写一个 TObjectList 的子类并添加一个自定义搜索方法,如下所示:
TSearchableObjectList<T:class> = class(TObjectList<T>)
public
function Search(aFound: TPredicate<T>): T;
end;
该方法的实现是
function TSearchableObjectList<T>.Search(aFound: TPredicate<T>): T;
var
item: T;
begin
for item in Self do
if aFound(item) then
Exit(item);
Result := nil;
end;
这种方法的一个例子是
var
myList: TSearchableObjectList<TActivitycategory>;
item: TActivitycategory;
searchKey: string;
begin
myList := TSearchableObjectList<TActivitycategory>.Create;
// Here you load your list
searchKey := 'WantedName';
// Let´s make it more interesting and perform a case insensitive search,
// by comparing with SameText() instead the equality operator
item := myList.Search(function(aItem : TActivitycategory): boolean begin
Result := SameText(aItem.FirstName, searchKey);
end);
// the rest of your code
end;
TPredicate<T>
上面使用的类型在 SysUtils
中声明,因此请务必将其添加到您的 uses 子句中。
我相信这是我们在 Delphi 中最接近 lambda 表达式的方法。
关于delphi - 搜索通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17730985/