In my application, _collection is a List from which I need to remove all User objects which do not match the criteria.
However, the fol
You can always start at the top index and iterate downward towards 0:
for (int i = _collection.Count - 1; i >= 0; i--)
{
User user = _collection[i];
if (!user.IsApproved())
{
_collection.RemoveAt(i);
}
}
Mehrdad's answer looks pretty darn elegant, though.
_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());
Whenever there is a chance that a collection will be modified in a loop, opt for a for
loop instead. The solution given by Mehrdad is lovely and definitely worth a try!
Here's code I find helpful when dealing with modifiable collections:
for(int index=0;index < _collection.Count; index++)
{
if (!_collection[index].IsApproved)
{
_collection.RemoveAt(index);
index--;
}
}