In my application, _collection is a List from which I need to remove all User objects which do not match the criteria.
However, the following code gets an invalid operation error in its second iteration since the _collection itself has been changed:
foreach (User user in _collection)
{
if (!user.IsApproved())
{
_collection.Remove(user);
}
}
I could create another List collection and copy them back and forth but then I have the issue of non-cloned reference types, etc.
Is there a way to do the above more elegantly than copying _collection to another another List variable?
_collection.RemoveAll(user => !user.IsApproved());
If you're still on 2.0:
_collection.RemoveAll(delegate(User u) { return !u.IsApproved(); });
By the way, if you don't want to touch the original list, you can get another list of approved users with:
_collection.FindAll(user => user.IsApproved());
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