开发者

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

开发者 https://www.devze.com 2023-01-11 01:56 出处:网络
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

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
      be开发者_Go百科gin
        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


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].


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 := TProduit(fProductList.Items[i]);    // this???
  end;
end;

You can then go:

MyProduit := getProductByName('banana');
MyProduit.StockQty := 3;

Or whatever you wish.


Your TProduit implements (Add). It doesn't already implement (Get) (or something similar)?

Are you inheriting this code? Is there more detail?

Edit: otherwise you'll have to create the Get procedure yourself, possibly by looping over the list and finding a match, then returning it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号