All, I have the following class structure
public class Foo : IComparable<Foo>
{
public List<Bar> Bars;
}
public class Bar : IComparable<Bar>
{
public List<Con> Cons;
}
public class Con : IComparable<Con>
{
...
}
I know how to remove object from a list
authorsList.RemoveAll(x => x.FirstName == "Bob");
But how, for my class above, do I remove a List<Con>
called badConList
, from my base object Foo
? Explicitly, the class hierarchy is populated like
Foo foo = new Foo();
foo.Bars = new List<Bar>() { /* Some Bar list */ };
foreach (Bar bar in foo.Bars)
bar.Cons = new List<Con>() { /* Some Con list */ };
// Now a bad Con list.
List<Con> badCons = new List() { /* Some bad Con list */ };
How do I remove the badCons
from foo
for each Bar
using LINQ?
Thanks for your time.
Ps. LINQ may not be the quickest method here; a simple loop might be (which is what LINQ will be doing under the hood anyway). Can you comment on this also?
You still can use RemoveAll
:
bar.Cons.RemoveAll(x => badCons.Contains(x));
An alternate solution would be to use a loop:
foreach(var badCon in badCons)
bar.Cons.Remove(badCon);
Both versions loop one of the lists multiple times:
badCons
N times with N being bar.Cons.Count()
. bar.Cons
N times with N being badCons.Count()
. If one of the two lists is magnitudes larger than the other, it is a good idea to choose the version that loops the large list only once, otherwise use the version that is simpler to understand to you and the readers of your codebase.
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.