如何使用Linq获取集合中的所有内容?

ror*_*yok 0 c# linq

我有一个方法可以接受一个可选int?值作为Take一个集合的项目.如果传递空值,我想返回所有项目.现在我必须复制我的查询才能完成此任务

if(take == null)
{
     x = db.WalkingDeadEps.Where(x => x.BicyclesCouldHaveSavedLives == true).ToList()
}
else
{
     x = db.WalkingDeadEps.Where(x => x.BicyclesCouldHaveSavedLives == true).Take(take).ToList()
}
Run Code Online (Sandbox Code Playgroud)

有更简单的方法吗?像这样的东西?

.Take(take != null ? take : "all")
Run Code Online (Sandbox Code Playgroud)

da_*_*rni 5

使用Linq,您可以选择将查询存储在变量中.直到你调用ToList它或等效的方法,它才会被执行.

var query = db.WalkingDeadEps.Where(x => x.BicyclesCouldHaveSavedLives == true);
x = take.HasValue ? query.Take(take.Value).ToList() : query.ToList();
Run Code Online (Sandbox Code Playgroud)