Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 according 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 List<int> type, it works nicely but I'd like to do that with my object. This object got an ID but I don't know how to use this ID inside the LINQ sentence.

like image 456
Dan-SP Avatar asked Oct 03 '11 16:10

Dan-SP


2 Answers

You need to compare the IDs:

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

List(T).RemoveAll

like image 147
Joe Avatar answered Sep 30 '22 15:09

Joe


who ever is viewing this now.I think var result = listA.Intersect(listB) will give the result for common values in the both the list.

like image 27
shahrukh_siddiqui Avatar answered Sep 30 '22 15:09

shahrukh_siddiqui