For all / for each loop through Delphi TCollection?
Does Delphi provide a good way to iterate over TCollectionItems in TCollection?
Something, perhaps line by line ...
for mycollectionitem in mycollection.Items do
mycollectionitem.setWhatever();
It doesn't compile though
or I really can't do anything that is more elegant than this:
for num := 1 to mycollection.Count do
mycollection.Items[num-1].setWhatever();
source to share
For..in
implemented as calls GetEnumerator
and methods of the return variable. The property is Items
not an object, but an array property that evenly maps a getter / setter pair, so it cannot return an enumerator, but TCollection
has a method itself GetEnumerator
.
Thus:
for mycollectionitem in mycollection do
mycollectionitem.setWhatever();
Remember, it is TCollection
not a generic class, so the type of the index variable of the enum will be TCollectionItem
, not whatever ItemClass
you are working with.
source to share