Resolved: Collection was modified; enumeration operation may not execute


I was playing with a data table object, my requirement was to merge all duplicate rows to one and remove the duplicates.
e.g.
Book     Price Quantity
Title 1 210   4
Title 1 210   6
Title 1 210   8

These were the rows inside my data table object. I want a consolidated row in place of these three duplicate rows.

Book     Price Quantity
Title 1 210   18

I used for each loop to add the quantity and then remove the rows but after executing this i got “Collection was modified; enumeration operation may not execute” error so i came to know that foreach statement uses an Enumerator, which is a little object optimized to move through a collection which doesn’t change.
So if we remove the items from the Enumerator, You are changing the contents of the list during enumeration which is the no-no being reported. The better way to handle would be to avoid changing such collections. So below is the code i used to resolve this:

for (int i = dtCartTable.Rows.Count – 1; i >= 0; i–)
{
DataRow dr = dtCartTable.Rows[i];

string dtitem = dr[“Book”].ToString();

if (dtitem == lblTitle.Text)
{
totalQuantity += Convert.ToInt32(dr[“Quantity”]);
dtCartTable.Rows.Remove(dr);
}

}
dtCartTable.AcceptChanges();

Voila its working now. Happy programming 🙂

Advertisements

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s