Search code examples
c#listlinqanyremoveall

How do I use Any() instead of RemoveAll() to exclude list items?


ListWithAllItems contains two type of items: ones I want select, and ones that I don't.

listForExcluding contains item that I should to exclude:

List<string> listForExcluding = ...;

So I do it in two strings:

List<string> x = ListWithAllItems.ToList();

x.RemoveAll(p => listForExcluding.Any(itemForExclude => itemForExclude == p));

How do I use Any() instead of RemoveAll() to get this query with one line?


Solution

  • Any doesn't make sense here, just use Except:

    var filtered = ListWithAllItems.Except(listForExcluding);
    

    ToList if you actually need a list at the end, otherwise don't realize IEnumerables for no reason (causes an extra enumeration).

    If you really want the RemoveAll version for some reason, use Contains (this is also how to do it using Where):

    x.RemoveAll(p => listForExcluding.Contains(p));
    

    There's a number of other valid lines... but seriously just go with Except