Error occurred. Collection was modified; enumeration operation might not execute

I have following piece of code in my project "foreach loop" throws the following excepiton "
Error occurred. Collection was modified; enumeration operation might not execute"

foreach (Assessment.tblMitchellLandscapeIDRow MitchellRow in objAssessment.tblMitchellLandscapeID.Rows)
{                                
     if (MitchellRow.AssessmentVersionID == AssessmentVersionID)
     DeleteMitchellLandscape(ref objAssessment, MitchellRow.MitchellID, UserFullname, ref ErrorMessage);
}

Open in new window


Delete mitchell landscape calls the following  but not sure why the foreach loop throws that exception. Some one please correct me what's the right way to handle this

        public bool DeleteMitchellLandscape(ref Assessment objAssessment, int MitchellIDToDelete, string UserFullname, ref string ErrorMessage)
        {
            string RowFilter = @"MitchellID=" + MitchellIDToDelete;
            Assessment.tblMitchellLandscapeIDRow[] mitchellLandscaperIdRowsows = (Assessment.tblMitchellLandscapeIDRow[])objAssessment.tblMitchellLandscapeID.Select(RowFilter);
            if ((mitchellLandscaperIdRowsows != null) && (mitchellLandscaperIdRowsows.Length != 0))
            {
                if (mitchellLandscaperIdRowsows.Length == 1)
                {
                    if (mitchellLandscaperIdRowsows[0].MitchellID > 0)
                    {
                        mitchellLandscaperIdRowsows[0].UpdatedBySystemUser = UserFullname;
                        mitchellLandscaperIdRowsows[0].SaveType = (int)EnumCollection.SaveType.RemoveOnly;

                    }
                    else
                    {
                        mitchellLandscaperIdRowsows[0].Delete();
                        objAssessment.AcceptChanges();
                    }
                }
                else
                {
                    //Cannot have more than one row with same key
                    ErrorMessage = "Error: More than one record found - Mitchell Landscape ID = " + Convert.ToString(MitchellIDToDelete);
                    return false;
                }
            }
            else
            {
                //Must have at least one row with same key
                ErrorMessage = "Error: Record not found - Mitchell Landscape ID = " + Convert.ToString(MitchellIDToDelete);
                return false;
            }
            return true;
        }

Open in new window

Sha1395Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

p_davisCommented:
your accessing/modifying objAssessment in a foreach that is iterating through it. you can't do that in a foreach... you could in a for but i still wouldn't recommend that
0
Sha1395Author Commented:
i agree but if i remove "objAssessment.AcceptChanges();" this piece of code from deletemitchelllandscape func , i don't have problem to execute the foreach loop and i can acceptChanges after foreach. What i am doing is correct or not i am not sure but solve my purpose to avoid throw exception but i want to learn the right way of approach.
0
p_davisCommented:
I guess you could call accept changes after the method call instead of in it.
0
it_saigeDeveloperCommented:
It is as davis has stated, however, the rows in objAssessment.tblMitchellLandscapeID.Rows are not actually affected until you call AcceptChanges.

Consider the following:
using System;
using System.Data;
using System.Linq;

namespace EE_Q28677811
{
	class Program
	{
		static void Main(string[] args)
		{
			DataTable table = GetTable();

			foreach (var row in table.Rows.OfType<DataRow>().AsEnumerable().Reverse())
			{
				Console.WriteLine("Deleting row - {0}", row["Drug"]);
				row.Delete();
				table.AcceptChanges();
			}
			Console.WriteLine("All rows deleted");

			table = GetTable();

			for (int i = table.Rows.Count - 1; i >= 0; i--)
			{
				Console.WriteLine("Deleting row - {0}", table.Rows[i]["Drug"]);
				table.Rows[i].Delete();
				table.AcceptChanges();
			}
			Console.WriteLine("All rows deleted");
			Console.ReadLine();
		}

		static DataTable GetTable()
		{
			DataTable table = new DataTable();
			table.Columns.Add("Dosage", typeof(int));
			table.Columns.Add("Drug", typeof(string));
			table.Columns.Add("Patient", typeof(string));
			table.Columns.Add("Date", typeof(DateTime));

			table.Rows.Add(25, "Indocin", "David", DateTime.Now);
			table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
			table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
			table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
			table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
			return table;
		}
	}
}

Open in new window

Which produces the following output -Capture.JPG-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.