LINQ: RemoveAll and get elements removed

Diego picture Diego · Apr 16, 2012 · Viewed 18.7k times · Source

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?

Answer

Amy B picture Amy B · Apr 16, 2012

I like to use a functional programming approach (only make new things, don't modify existing things). One advantage of ToLookup is that you can handle more than a two-way split of the items.

ILookup<bool, Customer> lookup = list.ToLookup(x => x.Condition);
List<Customer> sublist = lookup[true].ToList();
list = lookup[false].ToList();

Or if you need to modify the original instance...

list.Clear();
list.AddRange(lookup[false]);