Which is the easiest way to remove items that match some condition from a list and then, get those items.
I can think in a few ways, I don’t know which is the best one:
var subList = list.Where(x => x.Condition);
list.RemoveAll(x => x.Condition);
or
var subList = list.Where(x => x.Condition);
list.RemoveAll(x => subList.Contains(x));
Is any of this one of the best ways? If it is, which one? If it’s not, how should I do it?
I would go with the first option for readability purposes, with the note that you should materialize the list first, or you’ll lose the very items you’re trying to select on the next line:
The second example is O(n^2) for no reason and the last is perfectly fine, but less readable.
Edit: now that I reread your last example, note that as it’s written right now will take out every other item. You’re missing the condition check and the remove line should actually be
list.RemoveAt(i--);because thei+1th element becomes theith element after the removal, and when you incrementiyou’re skipping over it.