c#linq结合Expression< Func< T,bool>带有其他条件的where子句中的谓词 [英] c# linq combine Expression<Func<T, bool>> predicate in where clause with another condition
问题描述
var resultQuery = query.Where(q =>!q.IsDeleted&&谓词).ToList();
我想避免像这样的double where子句:
var resultQuery = query.Where(q =>!q.IsDeleted).Where(predicate).ToList();
这是不可能的.您需要提供一个lambda表达式作为 Where 子句的参数,该子句将被编译为表达式树,然后将其转换为某些SQL查询.在您的示例中
var resultQuery = query.Where(q =>!q.IsDeleted&& predicate).ToList();
您正在组合一个lambda表达式和一个布尔检查.避免出现两个 Where 子句的唯一方法是创建一个辅助函数,该函数返回用于过滤的lambda表达式,其中包括对 IsDeleted 标志和谓词逻辑即的过滤>
私有System.Linq.Expressions.Expression< Func< T,bool>filterPredicate(int n){返回q =>!q.IsDeleted&&q.年龄n;}
这里我们假设
q.年龄>n
是谓词函数的逻辑.然后使用这样的过滤谓词:
var resultQuery = query.Where(filterPredicate(5)).ToList();
有关lambda表达式和表达式树的更多信息,您可以在这里阅读 解决方案
IT is impossible. You need to provide a lambda expression as a parameter to the Where clause which would be compiled to an expression tree and after that translated into some SQL query. In your example
var resultQuery = query.Where(q => !q.IsDeleted && predicate).ToList();
you are combining a lambda expression and a boolean check. The only way to avoid the double Where clauses is to create a helper function that returns a lambda expression for filtering which includes filtering for the IsDeleted flag and the predicate logic i.e.
private System.Linq.Expressions.Expression<Func<T, bool>> filterPredicate(int n)
{
return q => !q.IsDeleted && q.Age > n;
}
Here we are assuming that
q.Age > n
is the logic of your predicate function. And then use the filter predicates like this:
var resultQuery = query.Where(filterPredicate(5)).ToList();
More about lambda expressions and expression trees you can read here https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1?view=net-5.0
这篇关于c#linq结合Expression< Func< T,bool>带有其他条件的where子句中的谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!