for all/for each looping through a Delphi TCollection?

delphi, loops, tcollection

Solution

`For..in` loops are implemented as calls to `GetEnumerator` and the methods on the variable it returns. The `Items` property is not an object, but an array property that maps silently to a getter/setter pair, so it can't return an enumerator, but `TCollection` itself does have a `GetEnumerator` method.

Thus:

for mycollectionitem in mycollection do
   mycollectionitem.setWhatever();

Be aware, though, that `TCollection` is not a generic class, so the type of the enumerator index variable will be `TCollectionItem`, and not whatever `ItemClass` you're working with.

Problem

Does Delphi provide any nice way to iterate over TCollectionItems in a TCollection? Something, perhaps, along the lines of... ``` for mycollectionitem in mycollection.Items do mycollectionitem.setWhatever(); ``` That doesn't compile though or is there really nothing I can do that's more elegant than this: ``` for num := 1 to mycollection.Count do mycollection.Items[num-1].setWhatever(); ```

Original source