简体   繁体   中英

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.

You need to compare the IDs:

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

List(T).RemoveAll

I believe you can use the Except Extension to do this.

var result = listA.Except(listB)

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

If you want to remove a 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> .

According to the documentation on MSDN ( http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx ), contains uses the default Equality comparer to determine equality, so you could use IEquatable's Equals method on your Obj class to make it work. HiperiX mentions the ref comparison above.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM