Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DeleteObject() in foreach loop

With Entity Framework, I try to delete some objects from my object context like that :

foreach (var item in context.Items.Where( i => i.Value > 50 ) )
{
   context.Items.DeleteObject(item);
}

With this code, I have a "Collection Was Modified" Exception.

So, how can I do a batch delete ?

like image 780
Patrice Pezillier Avatar asked Jul 08 '10 14:07

Patrice Pezillier


People also ask

How do I remove an object from an array in foreach?

Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable.

Can we remove any element by using it for each loop?

The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove . Therefore, the for-each loop is not usable for filtering.


2 Answers

You have to first get the items you want to delete out of the collection that you're going to modify. You can do this with a simple LINQ query (using ToList() to force execution):

var toDelete = context.Items.Where(i => i.Value > 50).ToList();

foreach(var item in toDelete)
{
    context.Items.DeleteObject(item);
}

Or if you like compact syntax (I don't, in this case), you could use:

context.Items
    .Where(i => i.Value > 50)
    .ToList()
    .ForEach(item => context.Items.DeleteObject(item));
like image 148
Justin Niessner Avatar answered Sep 18 '22 14:09

Justin Niessner


In a foreach, when the Collection is modified, you get the exception.

Solution: Copy your collection.

context.Items.Where( i => i.Value > 50 ).ToList().ForEach(item => context.Items.Remove(item));
like image 23
cRichter Avatar answered Sep 21 '22 14:09

cRichter