搜索通用列表 [英] search a Generic list
问题描述
我在修改一般搜索
因为我的类更复杂,我需要创建几个不同的搜索功能
I 'm trouble understanding in modifying the solution from GENERIC SEARCH as my class is more complex and I need to create several different search functions
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看起来像
Assume my TActivityCategory looks like
TActivityCategory = class
FirstName : String;
Secondname : String;
onemore .....
end;
如何对我的活动类中的每个String进行搜索?
How to implement a search for every String inside my activtity class ?
推荐答案
在你的位置,我将写一个TObjectList的子类,并添加一个如下所示的自定义搜索方法:
In your place I would write a subclass of TObjectList and add a custom Search method that would look like this:
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子句中。
The TPredicate<T>
type used above is declared in SysUtils
, so be sure to add it to your uses clause.
我相信这是最接近的我们可以在Delphi中找到lambda表达式。
I believe this is the closest we can get to lambda expressions in Delphi.
这篇关于搜索通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!