1

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:

  1. The first version loops badCons N times with N being bar.Cons.Count().
  2. The second version loops 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.

4

1 に答える 1

3

あなたはまだ使用することができますRemoveAll

bar.Cons.RemoveAll(x => badCons.Contains(x));

別の解決策は、ループを使用することです。

foreach(var badCon in badCons)
    bar.Cons.Remove(badCon);

どちらのバージョンも、リストの 1 つを複数回ループします。

  1. badCons最初のバージョンは N 回ループします。N はbar.Cons.Count()です。
  2. bar.Cons2 番目のバージョンは N 回ループします。N はbadCons.Count()です。

2 つのリストの一方が他方よりも大きい場合は、大きなリストを 1 回だけループするバージョンを選択することをお勧めします。それ以外の場合は、コードベースの読者にとって理解しやすいバージョンを使用してください。

于 2013-01-16T12:31:15.217 に答える