How to implement List.Remove against two different object list?

I have two lists : ListA<A> and ListB<B>

Structure of object:
Object A : - commonID , AName
Object B : - commonID , BName

Now my objective is very simple, I'm trying to remove all items in ListA that having the same commonID as in ListB. Below is what I've tried:

foreach(var item in ListB)
    ListA.Remove(x=>x.commonID == item.commonID)

It's throwing exception:

Cannot convert lambda expression to type 'A' because it is not a delegate type

May I know which part am I doing it wrong?

Jon Skeet
people
quotationmark

You're currently using Remove (which takes an individual item to remove) instead of RemoveAll (which takes a predicate).

However, a better approach might be to create a set of all IDs you want to remove, and then use a single call to RemoveAll:

HashSet<string> idsToRemove = new HashSet<string>(ListB.Select(x => x.commonID));
ListA.RemoveAll(x => idsToRemove.Contains(x.commonID));

Or if your lists are small enough that you're not worried about it being an O(N*M) operation, you can use:

ListA.RemoveAll(x => ListB.Any(y => x.commonID == y.commonID));

people

See more on this question at Stackoverflow