构建带有IsNullOrEmpty检查的Linq语句

本文关键字:Linq 语句 检查 IsNullOrEmpty 构建 | 更新日期: 2023-09-27 17:53:32

我怎样才能建立一个单一的Linq语句,它检查返回所有记录,除非参数被传递?如果param为空,则忽略特定的'where'。

我已经尝试在WHERE中使用IsNullOrEmpty,但我得到一个错误。

这里是用于搜索发票的非必需表单字段。

发票编号,支票编号,国家签发

var invoices = ctx.Invoices; <-- get all invoiced
if (inputInvoiceId > 0)
invoices = from i in invoices
where i.id == inputInvoiceId
select i;
if (!string.IsNullOrEmpty(inputCheckNumber))
invoices = from i in invoices
where i.checkNumber == inputCheckNumber
select i;
if (!string.IsNullOrEmpty(inputState))
invoices = from i in invoices
where i.state == inputState
select i;

构建带有IsNullOrEmpty检查的Linq语句

您可以通过有条件地附加where子句来构建查询,如下所示:

var invoices = ctx.Invoices.AsQueryable();
if (inputInvoiceId > 0)
    invoices = invoices.Where(x => x.id == inputInvoiceId);
if (!string.IsNullOrEmpty(inputCheckNumber))
    invoices = invoices.Where(x => x.checkNumber == inputCheckNumber);
if (!string.IsNullOrEmpty(inputState))
    invoices = invoices.Where(x => x.state == inputState);
return invoices.ToList();

每个额外的where子句进一步过滤您的结果,但查询本身不会被执行(也没有任何数据检索),直到您调用ToList()

@GrantWinney说的话会起作用。或者,您可以在单个查询中处理它,如果您关心这些事情,则可能有也可能没有查询编译/缓存好处:

// Query short-circuit parameters
var invoiceNotSpecified = inputVoiceId == 0;
var checkNumberNotSpecificed = String.IsNullOrEmpty(inputCheckNumber);
var stateNotSpecified = String.IsNullOrEmpty(inputState);
// Query
var invoices = from i in ctx.Invoices
     where (invoiceNotSpeficied || i.id == inputInvoiceId) && 
      (checkNumberNotSpecified || i.checkNumber == inputCheckNumber) && 
      (stateNotSpecified || i.state == inputState)
     select i;