Removing an Entity from an EntitySet during Iteration...

Posted by Gregorius on Stack Overflow See other posts from Stack Overflow or by Gregorius
Published on 2010-06-02T01:58:44Z Indexed on 2010/06/02 2:03 UTC
Read the original article Hit count: 503

Filed under:
|
|

I've got this code... seems nice and elegant, but apparently the framework don't like it when i mess with a collection while iterating through it:

foreach (KitGroup kg in ProductToTransfer.KitGroups)    
{    
// Remove kit groups that have been excluded by the user    
if (inKitGroupExclusions != null && inKitGroupExclusions.Contains(kg.KitGroupID))    
    ProductToTransfer.KitGroups.Remove(kg);    
else    
{    
// Loop through the kit items and do other stuff    
//...    
}    
}

The error it throws when it iterates to the 2nd object in the collection is: "EntitySet was modified during enumeration"

I know i could create a new collection of KitGroup objects (or even just IDs) that i want to remove, and then another loop afterwards to loop through these, and remove them from the collection, but this just seems like unnecessary extra code... can anybody suggest a more elegant way of achieving the same thing?

Cheers Greg

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET