[英]How can I use linq to search inside a list of objects
I am new in linq and I want to use it in a list without use a foreach
. 我是linq的新手,我想在列表中使用它而不使用
foreach
。 How can I return a list from a list of objects List<House>
where house ha swimming pool. 我如何从对象
List<House>
返回一个列表,其中房子是游泳池。
Class Houses
{
Int Id,
bool HasSwimmingPool
...
}
All you need is Where
method, which filters collection based of given predicate: 您需要做的只是
Where
方法,该方法根据给定谓词过滤集合:
var results = source.Where(x => x.HasSwimmingPool).ToList();
Additional ToList()
call makes the results List<House>
instead of IEnumerable<House>
. 额外的
ToList()
调用使结果为List<House>
而不是IEnumerable<House>
。
You can achieve the same using syntax-based query: 您可以使用基于语法的查询来实现相同目的:
var results = (from h in source
where h.HasSwimmingPool
select h).ToList();
That is simple: 很简单:
var yourCollection = new List<Houses>();
var housesThatHasASwimmingPool = yourCollection.Where(s => s.HasSwimmingPool);
try this: 尝试这个:
var swimmngHomes = listOfHouses.
Where( h => h.HasSwimmingPool == true);
List<Houses> housesWithPools = oldHouses.Where(x => x.HasSwimmingPool== true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.