Problem iterating over table rows with "foreach"


#1

Using "For Each" to iterate over table-rows throws the exception:

"Operation is not valid due to the current state of the object." at the statement "Next", in the following code fragment [run on the sample Invoice.doc]

Dim srcTbl As Table = doc.Sections(0).Body.Tables(4)

Dim destTbl As Table = doc.Sections(0).Body.Tables(5)

For Each row As Row In srcTbl.Rows

destTbl.Rows.Add(row.Clone(True))

Next

I get no errors with the equivalent, but less elegant, loop code:

For i As Integer = 0 To srcTbl.Rows.Count - 1

destTbl.Rows.Add(srcTbl.Rows(i).Clone(True))

Next

A minor quibble, but is there something in this kind of iteration I should watch out for?

Thanks.

-Charu Tevari


#2

Technically I must say it is pretty hard to efficiently maintain live collections of nodes and also iterators over them in sync with the document when the document is modified.

In this particular case adding a row to destTbl.Rows seems to invalidate the srcTbl.Rows collection. The enumerator simply gets invalidated (I don't think I can do anything better), but indexed access still works because the collection basically gets refreshed when accessed after it was invalidated.

Thanks for the report, I will check on this issue since I don't think the collection of rows should get invalidated unless maybe one table is nested inside another.


#3

Fixed in Aspose.Word 3.3.3