我有3种类型的对象,TypeA,TypeB,TypeC。 TypeA有一个TypeB列表,TypeB有一个TypeC列表,TypeC有一些我想跟踪的变量
Class TypeA
{
List<TypeB> MyListOfTypeB;
//...
}
Class TypeB
{
List<TypeC> MyListOfTypeC;
//...
}
Class TypeC
{
int SomeInteger;
//...
}
给定List<TypeA> MyListOfTypeA
,我想寻找满足特定条件的所有TypeC对象,例如,SomeInteger&gt; 100.除了为/ foreach循环嵌套之外,Linq的方法是什么?
答案 0 :(得分:4)
这就是你想要的东西我想:
var result = MyListOfTypeA.SelectMany(b => b.MyListOfTypeB.SelectMany(c => c.MyListOfTypeC.Select(x => x.SomeInteger > 100))).ToList();
答案 1 :(得分: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;
以上相当于调用SelectMany
LINQ函数,但在我看来它更清晰,更容易阅读。
使用LINQ函数(正如Dmitry已经建议的那样,但经过一些修改):
var cItems =
MyListOfTypeA.SelectMany( a => a.MyListOfTypeB )
.SelectMany( b => b.MyListOfTypeC )
.Where( c => c.SomeValue > 200 );
答案 2 :(得分: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;
答案 3 :(得分: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.