delphitcollection

delphi 7: How can I find item of object collection?


how can I find by name and get the Item in a collection of object ?

    procedure TfoMain.InitForm;
    begin
      // Liste des produits de la pharmacie 1
      FListeDispoProduit := TListeDispoProduit.Create(TProduit);

      with (FListeDispoProduit) do
      begin
        with TProduit(Add) do
        begin
          Name := 'Produit 01';
          CIP := 'A001';
          StockQty := 3;
          AutoRestock := 1;
          QtyMin:= 2;
        end;

        with TProduit(Add) do
        begin
          Name := 'Produit 02';
          CIP := 'A002';
          StockQty := 5;
          AutoRestock := 0;
          QtyMin:= 2;
        end;



 function getProductByName(productName: String): TProduit;
    var
      i : integer;
    begin
      for i := 0 to fProductList.Count -1 do
      begin
        if (TProduit(fProductList.Items[i]).Name = productName)
          Result :=
      end;
    end;

I want to edit qty about a product name.

How can I do this? thank you


Solution

  • If your collection object is a TCollection, then it has an Items property (which you should have been about to see in the documentation, or in the source code). Use that and its Count property to write a loop where you inspect each item to see whether it matches your target.

    var
      i: Integer;
    begin
      for i := 0 to Pred(FListeDespoProduit.Count) do begin
        if TProduit(FListeDespoProduit.Items[i]).Name = productName then begin
          Result := TProduit(FListeDespoProduit.Items[i]);
          exit;
        end;
      end;
      raise EItemNotFound.Create;
    end;
    

    Items is a default property, which means you can omit it from your code and just use the array index by itself. Instead of FListeDespoProduit.Items[i], you can shorten it to just FListeDespoProduit[i].