-1

I am trying to remove an element from Collection but ended up with error

Collection was modified; enumeration operation may not execute.

What i am trying to achieve?

Check Student list count in Report collection.

If count is == 1 Than check null or empty for Student properties

If all true than delete Student from Report collection..

Here is my code

public void Create(StudentReport report)
{

    ICollection<StudentReportDetails> student= report.Students;
    if (student.Count == 1) 

    {
        foreach (StudentReportDetails Studetails in student)
        {

            if (String.IsNullOrEmpty(Studetails.StudentNumber)&& String.IsNullOrEmpty(Studetails.Description) && String.IsNullOrEmpty(Studetails.Summary))
            {
                report.Students.Remove(Studetails);
            }

        }
    }
}
this
  • 5,229
  • 1
  • 22
  • 51
TheKingPinMirza
  • 7,924
  • 6
  • 51
  • 81

2 Answers2

2

Yes. You can't modify a collection. Foreach loop makes the collection as readonly.

Karthik
  • 1,064
  • 2
  • 16
  • 33
1

If you want to modify it change foreach to for loop:

for (int i = 0; i < student.Count; i++)
{ 

        if (String.IsNullOrEmpty(Studetails.StudentNumber)&& String.IsNullOrEmpty(Studetails.Description) && String.IsNullOrEmpty(Studetails.Summary))
        {
            report.Students.Remove(Studetails);
        }

    }
w.b
  • 11,026
  • 5
  • 30
  • 49