I have a question similar to this one, but pertaining to EntityCollection<>.
EntityCollection implements Remove(), allowing you to remove a single item from the list at once.  However, I'd like to implement an extension method that can remove multiple items at once, similar to IList<T>'s RemoveAll(Predicate<T> match) method.
One idea would be to loop through the list, and remove items. Something like:
public static void RemoveAll<T>(this EntityCollection<T> collection, Predicate<T> match) where T : EntityObject
{
   foreach (T o in collection)
   {
      if (match(o))
         collection.Remove(o);
   }
}
However, this will throw an exception because you can't modify the collection you're iterating through.
Another idea would be to build a temporary list of items to remove, then loop through that list and remove each item from the collection. However, this seems inefficient to me. Is there a better implementation?
As I said in comments, iterating over a secondary list is probably the only safe choice here.
You can implement it with something like:
public static void RemoveAll<T>(this EntityCollection<T> collection,
    Predicate<T> match) where T : EntityObject
{
    if (match == null) {
        throw new ArgumentNullException("match");
    }
    collection.Where(entity => match(entity))
              .ToList().ForEach(entity => collection.Remove(entity));
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With