简体   繁体   中英

remove from List using Linq

So, I have a List of objects of class A that contains a List of objects of class B

class A 
{
  ...
  List<B> bs;
}

and I have lists:

List<A> mainList;
List<B> listForRemoval;

How can I, using Linq, "clean" mainList, by removing all objects from bs (for every A in mainList) that exists in listForRemoval?

I hope I didn't confuse you with this question. :)

linq itself is probably not a great fit, but you can use some of it's extension methods. Linq typically is mostly for selection, not processing.

mainList.ForEach(x=>x.bs = x.bs.Where(y=>!listForRemoval.Contains(y)).ToList());

Yes, it's possible, as the other answers have shown. I would, however, choose the following solution which does not use LINQ at all:

foreach (var a in mainList) {
    a.bs.RemoveAll(b => listForRemoval.Contains(b));
}

Advantages:

  • It's easier to read and understand.
  • It's not longer than the LINQ-based solutions---in fact, it's shorter than the accepted, LINQ-based answer.
  • It removes the elements from bs rather than assigning a new list to bs. This might yield better performance and/or be necessary if the list is used in other places as well.
foreach (var list in mainList) {
    list.bs = list.bs.Where(b => !listForRemoval.Contains(b)).ToList();
}
mainList.ForEach(a => a.bs.RemoveAll(b => listForRemoval.Contains(b)));

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