Linq:有没有一种方法可以在对象列表中搜索符合条件的值
本文关键字:搜索 列表 对象 条件 有没有 方法 一种 Linq | 更新日期: 2023-09-27 17:58:17
我有三种类型的对象,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>100。除了嵌套for/foreach循环之外,Linq的方法是什么?
我想你正在寻找这样的东西:
var result = MyListOfTypeA.SelectMany(b => b.MyListOfTypeB.SelectMany(c => c.MyListOfTypeC.Select(x => x.SomeInteger > 100))).ToList();
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 );
使用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;
您需要浏览所有子列表,这就是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.