Reputation: 2221
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. :)
Upvotes: 2
Views: 4874
Reputation: 172220
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:
Upvotes: 4
Reputation: 28355
mainList.ForEach(a => a.bs.RemoveAll(b => listForRemoval.Contains(b)));
Upvotes: 2
Reputation: 32576
foreach (var list in mainList) {
list.bs = list.bs.Where(b => !listForRemoval.Contains(b)).ToList();
}
Upvotes: 2
Reputation: 880
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());
Upvotes: 4