Search code examples
delphipascallazarus

How to get the object of a TList in a TList?


Assume that I have a multiple objects stored in TO1 : TList then I create multiple TO1 and put all of them in TO2: TList. How can I get the value of selected object in a selected TO1 within TO2 ?


Solution

  • Since TList gives you pointers for each item, you have to cast the items to the proper datatypes:

    var
      aList: TList;
      aItem: TMyObject;
    begin
    
      aList := TList(TO2[selectedO2Index]);       // this cast isn't really needed
      aItem := TMyObject(aList[selectedO1Index]); // neither this one!
    
    end;
    

    You can save one variable by doing like this:

    var
      aItem: TMyObject;
    begin
    
      // Now the cast to TList is needed!
      aItem := TMyObject(TList(TO2[selectedO2Index])[selectedO1Index]);
    
    end;
    

    Depending on the Delphi version you are using, it would be more comfortable to use either TList<T> or TObjectList<T> generic class. No casts will be needed!