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;
Implementation for this method
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;
An example of this method is
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;
The TPredicate<T> type used above is declared in SysUtils , so be sure to add it to your uses section.
I believe this is the closest to what we can get in lambda expressions in Delphi.
source share