I'm trying to write an extension method in .NET that will operate on a generic collection, and remove all items from the collection that match a given criteria.
This was my first attempt:
public static void RemoveWhere<T>(this ICollection<T> Coll, Func<T, bool> Criteria){
foreach (T obj in Coll.Where(Criteria))
Coll.Remove(obj);
}
However this throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute". Which does make sense, so I made a second attempt with a second collection variable to hold the items that need to be removed and iterate through that instead:
public static void RemoveWhere<T>(this ICollection<T> Coll, Func<T, bool> Criteria){
List<T> forRemoval = Coll.Where(Criteria).ToList();
foreach (T obj in forRemoval)
Coll.Remove(obj);
}
This throws the same exception; I'm not sure I really understand why as 'Coll' is no longer the collection being iterated over, so why can't it be modified?
If anyone has any suggestions as to how I can get this to work, or a better way to achieve the same, that'd be great.
Thanks.
Another version of Marcs RemoveAll:
I just tried your second example and it seems to work fine:
I didn't get an exception.
For
List<T>
, this exists already, asRemoveAll(Predicate<T>)
. As such, I'd suggest that you keep the name (allowing familiarity, and precedence).Basically, you can't remove while iterating. There are two common options:
for
) and removalforeach
(as you've already done)So perhaps:
Or more generally for any
ICollection<T>
:This approach has the advantage of avoiding lots of extra copies of the list.
As Marc said,
List<T>.RemoveAll()
is the way to go for lists.I'm surprised your second version didn't work though, given that you've got the call to
ToList()
after theWhere()
call. Without theToList()
call it would certainly make sense (because it would be evaluated lazily), but it should be okay as it is. Could you show a short but complete example of this failing?EDIT: Regarding your comment in the question, I still can't get it to fail. Here's a short but complete example which works:
If you could provide a similar complete example which fails, I'm sure we can work out the reason.
I just tested it, and your second method works fine (as it should). Something else must be going wrong, can you provide a bit of sample code that shows the problem?
Gets: