Removing a list of objects from another list

I have been looking for something like this for several days. I am trying to remove all items from a larger list A according to list B.

Suppose I have a general list with 100 elements with different IDS, and I get another list with certain elements in just 10 entries. I need to remove all items from the first list, which does not exist in the second list.

I will try to show code that I really don’t know how it does not work.

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 do not know why, but it does not work. If I try this example with a List<int> , it will work well, but I would like to do this with my object. This object received an identifier, but I do not know how to use this identifier inside a LINQ clause.

+7
source share
4 answers

You need to compare identifiers:

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

List (T) .RemoveAll

+20
source

I believe that you can use the Except extension for this.

 var result = listA.Except(listB) 

Link: http://www.dotnetperls.com/except

+2
source

According to the MSDN documentation ( http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx ), the default comparison definition is used to determine equality, so you can use the IEquatable Equals method in your Obj class to he worked. HiperiX mentions link comparisons above.

How to add IEquateable interface: http://msdn.microsoft.com/en-us/library/ms131190.aspx

0
source

If you want to remove the list of objects ( listB ) from another list ( listA ), use:

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

Remember to use ToList () to convert IEnumerable<Obj> to List<Obj> .

0
source

All Articles