Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement RemoveAll() on EntityCollection<T>?

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?

like image 701
Mike Christensen Avatar asked Jan 14 '23 03:01

Mike Christensen


1 Answers

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));
}
like image 60
Frédéric Hamidi Avatar answered Jan 31 '23 07:01

Frédéric Hamidi