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 开发者_StackOverflow中文版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)));
精彩评论