LINQ: RemoveAll and get elements removed

c#, linq, removeall

Solution

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:

var sublist = list.Where(x => x.Condition).ToArray();
list.RemoveAll(x => x.Condition);

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 the `i+1`th element becomes the `i`th element after the removal, and when you increment `i` you're skipping over it.

Problem

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?

Original source