凡在LINQ谓词 [英] Where Predicates in LINQ

查看:125
本文介绍了凡在LINQ谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以指定具备条件的谓词LINQ中没有得到空引用异常。例如,如果是一个IQueryable我怎么可以这样做:

How can I specify conditions in Where predicates in LINQ without getting null reference exceptions. For instance, if q is an IQueryable how can I do like:

Expression<Func<ProductEntity,bool>> predicate = p => !search.CategoryId.HasValue || (search.CategoryId.HasValue && search.CategoryId == p.CategoryId);

var q2 = q.Where(predicate);

下面搜索是保存可能的对象可以或可以不设置像search.CategoryId检索条件可能没有设置,但如果它是我想获得由该条件设定的产品

Here search is an object that holds possible search conditions that may or may not be set like search.CategoryId might not be set but if it is I want to get the products that are set by that condition.

当我这样做,我得到空引用异常。

When I do this I get null reference exceptions.

推荐答案

您可以使用的空合并运算符 ?? 来替换默认值的可能的空值。下面套尝试,如果它存在或者干脆创建了一个总是为真的表现相匹配的search.Category。这将通过什么好的Linq查询提供商(例如LinqToSql)进行优化

You can use the null-coalescing operator ?? to replace a possible null value with a default value. The following sets tries to match the search.Category if it exists or simply creates an "always true" expression. This will be optimized by any good Linq query provider (e.g. LinqToSql).

Expression<Func<ProductEntity,bool>> predicate = (p => (search.CategoryId ?? p.CategoryId) == p.CategoryId));

var q2 = q.Where(predicate);



另一种可能是使用的 PredicateBuilder 。这就是我做了一个类似的模式搜索的方式为你使用:

Another possibility would be to dynamically compose a query predicate using PredicateBuilder. That's the way I do it for searches with a similar pattern as you use:

var predicate = PredicateBuilder.True<Order>();

if (search.OrderId))
{
   predicate = predicate.And(a => SqlMethods.Like(a.OrderID, search.OderID);  
}
// ...
var results = q.Where(predicate);

这篇关于凡在LINQ谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆