In Java I can iterate collection and remove some objects from it using Iterator.remove() method http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator.html#remove()
This is very handly and natural. Like you are looking for food in the fridge and throw away food with expired date. How to do the same in c#?
I want to iterate and clean-up collection in the same loop.
There are several related question, for example How to iterate and update a list however I still can not find exact duplicate of this operation in c#
If you’re using
List<T>, there’s a handy method to do this (RemoveAll), which will remove all elements which match a predicate (expressed as a delegate). For example:This is simpler than iterating backwards, IMO.
Of course, if you’re happy to create a new list instead, you can use LINQ: