2

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. :)

0

4 Answers 4

4

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());
Sign up to request clarification or add additional context in comments.

2 Comments

This will create many new instances of lists that are overrided.
@VMAtm - Yeah I would prefer a RemoveAll when dealing with List objects too because you don't know if there are lingering references out there. I was just showing using some of the linq extension methods. I was really just treating as if you were simply dealing with any "IEnumberable".
4

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.

2 Comments

I would suggest even when using the "RemoveAll" method there is no reason not to use the the "ForEach" method of the parent List like VMAtm did.
@Xenophile: Personally, I consider foreach (var x in list) ... to be easier to read than list.ForEach(x => ...) (especially if additional levels of nested parenthesis follow), but that might be a matter of taste.
2
foreach (var list in mainList) {
    list.bs = list.bs.Where(b => !listForRemoval.Contains(b)).ToList();
}

2 Comments

You need a "!" infront of contains.. you are doing the opposite of what he wanted with the sublist if I read that right.
@Xenophile - Oops. Thanks for the catch. Fixed it now.
2
mainList.ForEach(a => a.bs.RemoveAll(b => listForRemoval.Contains(b)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.