Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to foreach through a List<T> removing unwanted objects?

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?

like image 749
Edward Tanguay Avatar asked Jul 13 '09 15:07

Edward Tanguay


1 Answers

_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());
like image 87
mmx Avatar answered Oct 20 '22 15:10

mmx