When you create the list you can pass in a comparer. There are some comparer classes in the Generics.Defaults unit where you can pass in some anonymous method to compare two elements. They are used for several methods like IndexOf, Contains or Sort.
Example:
uses
Generics.Defaults,
Generics.Collections;
type
TActivityCategory = class
private
FName: string;
public
constructor Create(const Name: string);
property Name: string read FName write FName;
end;
constructor TActivityCategory.Create(const Name: string);
begin
FName := Name;
end;
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));
activities.Add(TActivityCategory.Create('Category B'));
activities.Add(TActivityCategory.Create('Category C'));
activities.Add(TActivityCategory.Create('Category A'));
search := TActivityCategory.Create('Category C');
if activities.Contains(search) then
ShowMessage('found');
ShowMessageFmt('Index: %d', [activities.IndexOf(search)]);
activities.Sort;
ShowMessageFmt('Index: %d', [activities.IndexOf(search)]);
search.Name := 'Category D';
if not activities.Contains(search) then
ShowMessage('not found');
search.Free;
activities.Free;
end;
Comparer
in Cosmin's answer and replace the internals withResult := CompareText(L.Name, R.Name)
, or useCompareStr
for case-sensitive comparison. Cosmin was talking about binary search. If you don't want to sort your container you are into linear search. Use IndexOf in that case. – CelsacelsiusIndexOf
? I thought it would always do a byte-wise comparison. Since the OP wants to search only for the name field, he would have to implement the linear search on his own (as trivial as it is) – Adoration