考虑这个功能:
public List<Employees> getEmployees(....... , int? takeMax = null)
{
// some code
...
var items = DB_Context.Employees.Where(%%%%% WHATEVER %%%%).Take(takeMax.HasValue && takeMax.Value > 0 ? takeMax.Value : ?????? ).ToList();
}
如果takeMax
为NULL,我如何获取所有项目?
Take()
需要int
,我不想写类似
int total = DB_Context.Employees.Count();
var items = DB_Context.Employees.Where(%%%%% WHATEVER %%%%).Take(takeMax.HasValue && takeMax.Value > 0 ? takeMax.Value : total ).ToList();
任何替代方案?
答案 0 :(得分:4)
你只能在这种情况下应用拍摄:
var itemsQuery = DB_Context.Employees.Where(%%%%% WHATEVER %%%%);
if (takeMax > 0)
{
itemsQuery = itemsQuery.Take(takeMax);
}
var items = itemsQuery.ToList();
答案 1 :(得分:3)
这是一种方法,你仍然需要写两行(比如你的计数例子),但你不必计算Count
。
var query = DB_Context.Employees.Where(%%%%% WHATEVER %%%%);
var items = takeMax.HasValue && takeMax.Value > 0 ?
query.Take(takeMax.Value).ToList() : query.ToList();
答案 2 :(得分:0)
也许是这样的:
public List<Employees> getEmployees(....... , int? takeMax = null)
{
// some code
...
if(takeMax != null)
{
return DB_Context.Employees.Where(%%%%% WHATEVER %%%%).Take(takeMax).ToList();
}
else
{
return return DB_Context.Employees.Where(%%%%% WHATEVER %%%%).ToList();
}