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
pro
In your place I would write a subclass of TObjectList and add a custom Search method that would look like this:
TSearchableObjectList = class(TObjectList)
public
function Search(aFound: TPredicate): T;
end;
The implementation for that method is
function TSearchableObjectList.Search(aFound: TPredicate): T;
var
item: T;
begin
for item in Self do
if aFound(item) then
Exit(item);
Result := nil;
end;
An example of this method is
var
myList: TSearchableObjectList;
item: TActivitycategory;
searchKey: string;
begin
myList := TSearchableObjectList.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;
The TPredicate
type used above is declared in SysUtils
, so be sure to add it to your uses clause.
I believe this is the closest we can get to lambda expressions in Delphi.