Problem removing entity out of collection

Posts   
 
    
Fishy avatar
Fishy
User
Posts: 392
Joined: 15-Apr-2004
# Posted on: 28-Jun-2005 18:52:19   

I don't think it's a problem with llbl per se.

Here's the code:

        For Each Student As Student In gGlobalVars.GradeBookStudents
            For Each SubjectAreaTchr As SubjectAreaTchrStudEntity In Student.StudentEntity.SubjectAreaTchrStud
                If SubjectAreaTchr.SubAreaTchrIdent = -1 Then
                    Student.StudentEntity.SubjectAreaTchrStud.Remove(SubjectAreaTchr)
                End If
            Next
        Next

Here's the Error:

 ************** Exception Text **************
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.Collections.ArrayListEnumeratorSimple.MoveNext()
   at MedfordSchoolDistrict.ElementaryGradeBook.frmSubjectAreaTeacher.frmSubjectAreaTeacher_Closing(Object sender, CancelEventArgs e) in C:\Documents and Settings\dave.vorgang\My Documents\Visual Studio Projects\ElementaryTeachersDesktop\ElementaryGradeBook\frmSubjectAreaTeacher.vb:line 233

I'm guessing that it doesn't like me removing items while i'm running thru the collection. disappointed

So, how do I accomplish what I want to do?

Thanks,

Fishy

Fishy avatar
Fishy
User
Posts: 392
Joined: 15-Apr-2004
# Posted on: 28-Jun-2005 19:08:11   

I think this will remove it:

        For Each Student As Student In gGlobalVars.GradeBookStudents
            For Each SubjectAreaTchr As SubjectAreaTchrStudEntity In Student.StudentEntity.SubjectAreaTchrStud
                If SubjectAreaTchr.SubAreaTchrIdent = -1 Then
                    SubjectAreaTchr = Nothing
                End If
            Next
        Next

Just setting it to Nothing instead of removing from collection.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39933
Joined: 17-Aug-2003
# Posted on: 28-Jun-2005 20:31:33   

You can't modify anything in a collection you're using in a foreach simple_smile . You have to add the elements to remove to an arraylist, then foreach over that to remove it from the other collection.

Frans Bouma | Lead developer LLBLGen Pro
mattlant
User
Posts: 16
Joined: 24-Jun-2005
# Posted on: 28-Jun-2005 20:42:30   

if you are worried about performnace you can also use a for loop instead. When you hit an element you need to remove just decrement your counter by one.

Matt