delphi-7tlist

Searching for a Corresponding Value in a TList Delphi7


I have a TList which I populate dynamically, from the database, it contains an ID and Name.

What I need to know is how to search for a certain Name in that TList by providing an ID without using for loop.


Solution

  • without using for loop

    Unfortunately, that is exactly what you must use. A TList containing pointers only knows how to search for pointers, nothing else. To do what you are wanting, you must loop through the list dereferencing the pointers manually in order to compare their field values.

    For example:

    type
      TDatabaseRecord = class
      public
        ID: Integer;
        Name: String;
      end;
    
    function FindNameByID(ID: Integer): String;
    var
      I: Integer;
    begin
      Result := '';
      for I := 0 to MyList.Count-1 do
      begin
        if TDatabaseRecord(MyList[I]).ID = ID then
        begin
          Result := TDatabaseRecord(MyList[I]).Name;
          Exit;
        end;
      end;
    end;