3

我有 3 种类型的对象,TypeA、TypeB、TypeC。TypeA 有一个 TypeB 列表,TypeB 有一个 TypeC 列表,TypeC 有一些我想跟踪的变量

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

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

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

给定 a List<TypeA> MyListOfTypeA,我想查找所有满足特定条件的 TypeC 对象,例如 SomeInteger > 100。除了嵌套 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
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 回答
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 回答
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 回答