score:7

Accepted answer

The simplest way would be to do this:

foreach(var item in bList) aList.Remove(item);

Remove doesn't do anything if the item isn't already in the list.

If by "use LINQ" you mean use LINQ to determine if an item in aList is in bList, that's not necessary.

A LINQ solution would be more efficient ONLY if both of these conditions are true:

  1. aList is very small compared to bList
  2. All of the items in aList that are also in bList are at the very beginning of bList

score:0

Check out the LINQ "Except" extension:

http://www.dotnetperls.com/except

Except subtracts elements from a collection. This extension method is found in the System.Linq namespace in the .NET Framework. It essentially subtracts all the elements in one collection from another.

score:8

Take a look at List<T>.RemoveAll

aList.RemoveAll(x => bList.Contains(x))

FWIW, this will also remove all objects in aList contained in bList, not only the first instance of each bList object in aList, if this is important.

score:2

You can use the Except extension method:

var result = aList.Except(bList);

Note that you can also pass an IEqualityComparer<T> as a second argument if you need to customize the equality checking.


Related Articles