3

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();
Jessica Brown
  • 8,222
  • 7
  • 46
  • 82

1 Answers1

6

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.

TLama
  • 75,147
  • 17
  • 214
  • 392
Mason Wheeler
  • 82,511
  • 50
  • 270
  • 477
  • 2
    Also keep in mind that `for..in` was introduced in Delphi 2007, so it won't work for older versions. – Remy Lebeau Nov 20 '14 at 03:32
  • @Remy: Yes, but considering that the OP is using `for..in` syntax in the example, it's reasonable to assume he's working with a version that supports it. – Mason Wheeler Nov 20 '14 at 03:34
  • 1
    The OP *wants* to use `for..in` syntax. That does not mean he actually *has* a Delphi version that supports `for..in` loops. Some other languages have similar `for..in` syntax, so he could just be speculating. He did not say anything that hints at the Delphi version he is using. – Remy Lebeau Nov 20 '14 at 03:37