views:

233

answers:

1

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

+3  A: 
foreach (KitGroup kg in ProductToTransfer.KitGroups.ToList())    
{    
 // 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    
 //...    
 }    
}

or if KitGroups is of type List<T> already...

if(inKitGroupExclusion != null)
    ProductToTransfer.KitGroups.RemoveAll(x => inKitGroupExclusion.Contains(x));
foreach (KitGroup kg in ProductToTransfer.KitGroups)    
{    
    // Loop through the kit items and do other stuff    
    //...    
}

You can also use this second method on another IEnumerable<T> if you want to define the RemoveAll() behavior with an extension method. Be sure you don't try to use the RemoveAll() on a LINQ entity table because the inKitGroupExclusion.Contains() won't get translated into SQL.

Edit: just realized that it's not a list, just an EntitySet, so you will need to go with the first method.

Jake
Wow awesome... all i needed to do was convert it to a List. So its just because it was an EntitySet that i couldn't delete collection items in an enumeration... why is this?Thanks heaps, i knew there'd be an easy solution to this probleM :)
Gregorius
@Gregorius It's not the fact that it's an `EntitySet`, it's the fact that you're deleting from the object you're enumerating over. Calling `ToList` instantiates a new `List` object to enumerate over while you delete from the original `EntitySet`. You would have to use the same sort of procedure to delete items from a `List` or any other collection.
Jake
ahhh... that makes perfect sense. thanks Jake, much appreciated
Gregorius