I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from
If the function that determines which items to delete has no side effects and doesn't mutate the item (it's a pure function), a simple and efficient (linear time) solution is:
list.RemoveAll(condition);
If there are side effects, I'd use something like:
var toRemove = new HashSet();
foreach(var item in items)
{
...
if(condition)
toRemove.Add(item);
}
items.RemoveAll(toRemove.Contains);
This is still linear time, assuming the hash is good. But it has an increased memory use due to the hashset.
Finally if your list is only an IList
instead of a List
I suggest my answer to How can I do this special foreach iterator?. This will have linear runtime given typical implementations of IList
, compared with quadratic runtime of many other answers.