If your For Each loop reaches the new BlockReferences created by
exploding ones it encounters, then i don't see a problem except that
in most designs that involve iterators, changing the sequence of items
that are being iterated over is considered an error (for example, if you
try iterating over a List<T>, and you add/remove/change elements, it
throws an exception). If AutoCAD's BlockTableRecord enumerator does
not do that, then you are relying on undocumented behavior that may
change in the future.
In any case, you might want to wrap the call to ExplodeToOwnerSpace()
in a try/catch block, since not every BlockReference can be exploded.
This code works so that no matter how deeply nested the blocks may be, you end up with a drawing with no blocks. My question is: is my code an effective and proper way to do this?
Dim db As Database = HostApplicationServices.WorkingDatabase()
Using trans As Transaction = db.TransactionManager.StartTransaction()
Dim bt As BlockTable = DirectCast(trans.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)
Dim btr As BlockTableRecord = TryCast(bt(BlockTableRecord.ModelSpace).GetObject(OpenMode.ForRead), BlockTableRecord)
Dim bClass As RXClass = RXClass.GetClass(GetType(BlockReference))
For Each oid As ObjectId In btr
If (oid.ObjectClass = bClass) Then
Dim blkRef As BlockReference = TryCast(trans.GetObject(oid, OpenMode.ForWrite, False), BlockReference)
blkRef.ExplodeToOwnerSpace()
blkRef.Erase(True)
End If
Next
trans.Commit()
End Using
Thanks,
Ted