Remove all entries from collection, which are found in different collection using linq

Viewed 38

Lets say we have two lists:

List<string> listA = new List<string>{"a", "c"};
List<string> listB = new List<string>{"a", "a", "b", "c", "d"};

And we want to remove from listB all duplicates with listA.

listA should be left untouched

listB should be left with elements {"b", "d"}

An obvious solution would be to iterate with loops, but I'm wondering how this can be done with System.Linq one-liner?

Maybe something like...

listB.RemoveAll(x => x.Equals(??));

Or...

listA.ForEach(key => listB.RemoveAll(x => x.Equals(key))); // cannot convert string[] to void
2 Answers

You can use Except:

listB = listB.Except(listA).ToList();

a less efficient LINQ version:

listB = listB.Where(b => !listA.Contains(b)).ToList();

a non LINQ version which does not need to create a new list:

listB.RemoveAll(listA.Contains);

A possibly more performant version of @TimSchmelter's non-LINQ RemoveAll uses a HashSet:

var hashA = new HashSet<string>(listA);
listB.RemoveAll(hashA.Contains);
Related