在LINQ中取所有的三元运算符

本文关键字:三元 运算符 LINQ | 更新日期: 2023-09-27 18:16:40

考虑这个函数:

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();

有其他选择吗?

在LINQ中取所有的三元运算符

您只能在这种情况下应用take:

var itemsQuery = DB_Context.Employees.Where(%%%%% WHATEVER %%%%);
if (takeMax > 0)
{
  itemsQuery  = itemsQuery.Take(takeMax);
}
var items = itemsQuery.ToList();

这是一种方法,您仍然需要编写两行(就像您的计数示例一样),但您不必计算Count

var query = DB_Context.Employees.Where(%%%%% WHATEVER %%%%);
var items = takeMax.HasValue && takeMax.Value > 0 ? 
                query.Take(takeMax.Value).ToList() : query.ToList();

可能像这样:

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();
}