0

I'm aware that this question is asked on here a lot, but I'm unable to gather a correct answer based on my specific loop.

I'm using a foreach loop to cycle through a Business Entity like so:

foreach (Content item in category) { item.Stats = 55; item.Commit(); } 

The foreach loop runs correctly for the first item it retrieves and places the value but breaks shy of the other few and I get the error in my page title. I'm aware that I'm getting the error because the item cannot be modified during iteration. But I'm at a lost as to how else to commit to the database while in this loop.

Thanks in advance.

4
  • 1
    It sounds like your Commit function is modifying the item in some way. Can you post the code to that function? Commented Apr 11, 2013 at 21:09
  • Is your Commit function modifying Category? Is Category an observable collection? Commented Apr 11, 2013 at 21:16
  • 2
    The collection cannot be modified. The items themselves can. Commented Apr 11, 2013 at 21:16
  • The Commit function is just simply saving the Stats figure to the db. The function is trying to modify the 'Content item' values. Not necessarily the collection. Commented Apr 11, 2013 at 21:20

2 Answers 2

1

You could create an identical collection with clones of your items, and instead of modifying that items in your iterated collection, modify and commit the corresponding items in the cloned collection. Then discard your iterated collection when finished, treating your cloned collection as the new "originals".

Sign up to request clarification or add additional context in comments.

2 Comments

Can you give me a code example? The category object is a BusinessEntityList and gets defined like so: BusinessEntityList<Content> category = SiteCategories.Filter(new ContentFilter(true));
Right. That worked out I created a clone List<> with the items and ran a loop to save with that list.
0

Simplest solution to this would be adding ToList() which results in enumerating over copy of the original enumeration.

foreach (Content item in category.ToList()) { item.Stats = 55; item.Commit(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.