Daniel Grillo
Daniel Grillo

Reputation: 2418

How can I update a data in a TList<T>?

I have this record (structure):

type
    THexData = record            
            Address : Cardinal;
            DataLen : Cardinal;
            Data    : string;    
    end;

And I've declared this list:

HexDataList: TList<THexData>;

I've filled the list with some data. Now I'd like scan ListHexData and sometimes update a element of a record inside HexDataList.

Is it possible? How can I do?

Upvotes: 2

Views: 2541

Answers (1)

David Heffernan
David Heffernan

Reputation: 612964

var
  Item: THexData;
... 
for i := 0 to HexDataList.Count-1 do begin
  Item := HexDataList[i];
  //update Item
  HexDataList[i] := Item;
end;

The bind is that you would like to modify HexDataList[i] in place, but you can't. When I'm working with a TList<T> that holds records I actually sub-class TList<T> and replace the Items property with one that returns a pointer to the item, rather than a copy of the item. That allows for inplace modification.

EDIT

Looking at my code again I realise that I don't actually sub-class TList<T> because it the class is too private to extract pointers to the underlying data. That's probably a good decision. What I actually do is implement my own generic list class and that allows me the freedom to return pointers to records if needed.

Upvotes: 8

Related Questions