1

I am sorry to ask this question again, i was going thru other post related to this one but can't understand how to modify my code based on answers, so i post it here for help.

Following code throws the exception and i wast trying to modify my code like the one suggested in other post enter link description here

foreach (Assessment.tblMitchellLandscapeIDRow MitchellRow in objAssessment.tblMitchellLandscapeID.Rows)
{                                
     if (MitchellRow.AssessmentVersionID == AssessmentVersionID)
     DeleteMitchellLandscape(ref objAssessment, MitchellRow.MitchellID, UserFullname, ref ErrorMessage);
}
Community
  • 1
  • 1
Usher
  • 2,146
  • 9
  • 43
  • 81
  • 1
    You cannot modify your collection (Your rows from tblMitchellLandscapeID) while iterating over it with a foreach statement. I guess that's what your Delete method is doing. – Pierre-Luc Pineault May 21 '15 at 01:19
  • Use a `for` loop rather than a `foreach`. And iterate it in reverse if you are going to delete items from the list during the loop - it saves you from having to adjust your indexer. – slugster May 21 '15 at 01:20
  • The link you posted as for answers For loops not foreach. – andrew May 21 '15 at 01:21
  • If using a 'for' loop, remember to subtract one from the loop counter each time you delete a row. – Carl Prothman May 21 '15 at 02:41

1 Answers1

1

You can't alter a collection that you are iterating through.

As some commenter's have suggested, use a for loop, or build up a collection of the items you want to delete in the loop, then delete them afterwards. You might also need to modify your DeleteMitchellLandscape method.

var deleteList = new List<Assessment.tblMitchellLandscapeIDRow>();
foreach (Assessment.tblMitchellLandscapeIDRow MitchellRow in objAssessment.tblMitchellLandscapeID.Rows)
{                                
     if (MitchellRow.AssessmentVersionID == AssessmentVersionID)
         deleteList.Add(MitchellRow);
}

DeleteMitchellLandscape(ref objAssessment, deleteList, UserFullname, ref ErrorMessage);
Steve
  • 9,335
  • 10
  • 49
  • 81