Yip*_*Yay 21 c# expression negate
我正在寻找一种方法来否定用于过滤IQueryable序列的表达式.
所以,我有类似的东西:
Expression<Func<T, bool>> expression = (x => true);
Run Code Online (Sandbox Code Playgroud)
现在我希望创建一个会导致屈服的表达式(x => false)- 所以我基本上想要否定它expression.
我发现自己的工作方法是这样的:
var negatedExpression =
Expression.Lambda<Func<T, bool>> (Expression.Not(expression.Body),
expression.Parameters[0])));
Run Code Online (Sandbox Code Playgroud)
但我几乎肯定有更好的方法 - 你能帮助我吗?(Not(expression)可能是这样的).
Che*_*hen 20
一种简单的扩展方法:
public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> one)
{
var candidateExpr = one.Parameters[0];
var body = Expression.Not(one.Body);
return Expression.Lambda<Func<T, bool>>(body, candidateExpr);
}
Run Code Online (Sandbox Code Playgroud)
用法:
Expression<Func<int, bool>> condition = x => x > 5;
var source = Enumerable.Range(1, 10);
var result1 = source.Where(condition.Compile()); //6,7,8,9,10
var result2 = source.Where(condition.Not().Compile()); //1,2,3,4,5
Run Code Online (Sandbox Code Playgroud)