3

TypeA、TypeB、TypeCの3種類のオブジェクトがあります。TypeAにはTypeBのリストがあり、TypeBにはTypeCのリストがあり、TypeCには追跡したい変数がいくつかあります

Class TypeA
{
  List<TypeB> MyListOfTypeB;
  //...
}

Class TypeB
{
  List<TypeC> MyListOfTypeC;
  //...
}

Class TypeC
{
  int SomeInteger;
  //...
}        

が与えられたList<TypeA> MyListOfTypeA場合、SomeInteger > 100 などの特定の条件を満たすすべての TypeC オブジェクトを探したいと思います。for/foreach ループをネストする以外に、これを行う Linq の方法は何ですか?

4

4 に答える 4

4

このようなものは、あなたが探しているものだと思います:

var result = MyListOfTypeA.SelectMany(b => b.MyListOfTypeB.SelectMany(c => c.MyListOfTypeC.Select(x => x.SomeInteger > 100))).ToList();
于 2013-02-07T19:07:29.717 に答える
3

Linqを使用して次の方法で実行できます。

    var myListOfTypeA = new List<TypeA>();

    // fill your list here

    var typeCs = from typeA in myListOfTypeA
                 from typeB in typeA.MyListOfTypeB
                 from typeC in typeB.MyListOfTypeC
                 where typeC.SomeInteger > 100
                 select typeC;
于 2013-02-07T19:04:22.720 に答える
3
var MyListOfTypeA = new List<TypeA>();
// ...
var cItems = 
    from a in MyListOfTypeA
    from b in a.MyListOfTypeB
    from c in a.MyListOfTypeC
    where c.SomeInteger > 100
    select c;

上記はSelectManyLINQ 関数の呼び出しと同等ですが、私の意見では、はるかにクリーンで読みやすいと思います。

LINQ関数でそれを行う(Dmitryによってすでに提案されていますが、いくつかの変更があります):

var cItems = 
    MyListOfTypeA.SelectMany( a => a.MyListOfTypeB )
                 .SelectMany( b => b.MyListOfTypeC )
                 .Where( c => c.SomeValue > 200 );
于 2013-02-07T19:02:01.797 に答える
2

すべてのサブリストをナビゲートする必要があり、それがfromできることです。

var ta = new TypeA();

var allTypeCsThatSatisfyMyCondition = 
    from tb in ta.MyListOfTypeB                     // This will iterate to each item in the list
    from tc in tb.MyListOfTypeC                     // This will iterate to each item in the *sublist*
    where tc.SomeInteger > 100          // Condition could be anything; filter the results
    select tc;                                      // When you select, you tell your iterator to yield return that value to the caller.

return allTypeCsThatSatisfyMyCondition.ToList();    // To list will force the LINQ to execute and iterate over all items in the lists, and add then to a list, effectively converting the returned items to a list.
于 2013-02-07T19:20:56.277 に答える