Dan-SP Dan-SP - 1 year ago 92
C# Question

Removing a list of objects from another list

I've been looking for something like that for days. I'm trying to remove all the elements from a bigger list A accoring to a list B.

Suppose that I got a general list with 100 elements with differents IDS and I get another list with specific elements with just 10 records. I need remove all the elements from the first list that doesn't exists inside the second list.

I'll try to show the code that I actually don't know how it didnt works.

List<Obj> listA = new List<Obj>();
List<Obj> listB = new List<Obj>();

//here I load my first list with many elements
//here I load my second list with some specific elements

listA.RemoveAll(x => !listB.Contains(x));

I don't know why but it's not working. If I try this example with a
type, it works nicelly but I'd like to do that with my object. This object got an ID but I dont know how to use this ID inside the LINQ sentence..

Thaks for the help !

Joe Joe
Answer Source

You need to compare the IDs:

listA.RemoveAll(x => !listB.Any(y => y.ID == x.ID));


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download