仅当参数在linq中具有值时才应用筛选器

  • 本文关键字:应用 筛选 参数 linq c# linq
  • 更新时间 :
  • 英文 :


Iam使用LINQ从数据库中检索记录。一切都很好,只是我需要在一个查询中应用不同的过滤器。如果参数不为Null且大于零,则应用筛选器。否则,如果它们为Null或零,则不应用筛选器。以下是示例:

bankId(int) and accountNumber(string) are my two parameters.
if bankId > 0 then get the records matching the bankId, if accountnumber is passed then get the records matching the accountnumber.
If both are passed pull all the records matching with bankid and accountnumber.
If both are not passed then return all records without applying filter.

目前我能够做到这一点,在不应用任何过滤器的情况下,我获取所有记录,然后如果通过了bankId,则对上述结果应用过滤器,如果再次通过了accountnumber,则对以上结果应用过滤器。

但这里的问题是,这种方法会导致我不想要的多重if条件。

有没有什么最好简单的方法可以在单个查询中应用这些过滤器并获得结果?

请建议,提前谢谢。

以这种方式构建您的语句

var items = context.accounts.AsQueryable();
if (bankId > 0)
{
items = items.Where(x => x.bankId == bankId);
}
if (!string.IsNullOrEmpty(accountnumber))
{
items = items.Where(x => x.accountnumber == accountnumber);
}
var result = items.ToList(); // query db / materialize here!

您可以使用LINQ操作定义一个函数并通过该函数进行筛选。C#支持linq操作中的函数式编程。

下面我定义了一个函数(filterAccounts(,如果满足要求,它将返回布尔值。

之后,我将此函数作为参数发送到LinqWhere方法。Where方法调用每个元素的filterAccounts方法,如果返回true,则生成它,并最终返回所有返回true的元素。

我希望它能有所帮助。

List items = getItemsAslist();

Func<item, bool> filterAccounts = (i) => 
{
return (bankId > 0 ? i.bankId == bankId : true) 
&& (!string.IsNullOrEmpty(accountnumber) ? accountNumber == i.accountNumber : true)
};

items = items.Where(filterAccounts);

最新更新