IQueryable的< T>。凡()适合防爆pression在哪里?适合、LT、IQueryable、pression

2023-09-03 13:49:31 作者:如儿戏

我是非常低的经历与防爆pressions 在.NET中,这就是为什么我宁愿问你们。 我应该如何 - 看看下面的评论:

I'm very low experienced with Expressions in .NET, that's why I rather ask you guys. How should I - see comment below:

using P = Myclass;
..
System.Linq.Expressions.Expression<Func<P, bool>> myExpression = null;
..
myExpression1 = x => foo1 == true && foo2 == false;
myExpression2 = x => ... ;
..
BinaryExpression resultExpression = System.Linq.Expressions.Expression.OrElse(myExpression1, myExpression2);
..
IQueryable<P> l = l.Where(?resultExpression?); // how to transform BinaryExpression to the suitable type?

感谢您

推荐答案

您不能或lambda表达式在一起的方式。你真的想或拉姆达机构一起。这里有一个方法来做到这一点:

You can't "OR" lambdas together that way. You really want to "OR" the lambda bodies together. Here's a method to do that:

public static Expression<Func<T, bool>> OrTheseFiltersTogether<T>( 
  this IEnumerable<Expression<Func<T, bool>>> filters) 
{ 
    Expression<Func<T, bool>> firstFilter = filters.FirstOrDefault(); 
    if (firstFilter == null) 
    { 
        Expression<Func<T, bool>> alwaysTrue = x => true; 
        return alwaysTrue; 
    } 

    var body = firstFilter.Body; 
    var param = firstFilter.Parameters.ToArray(); 
    foreach (var nextFilter in filters.Skip(1)) 
    { 
        var nextBody = Expression.Invoke(nextFilter, param); 
        body = Expression.OrElse(body, nextBody); 
    } 
    Expression<Func<T, bool>> result = Expression.Lambda<Func<T, bool>>(body, param); 
    return result; 
} 

再后来:

Expression<Func<P, bool>> myFilter1 = x => foo1 == true && foo2 == false;  
Expression<Func<P, bool>> myFilter2 = x => ... ;  
..  
List<Expression<Func<P, bool>>> filters = new List<Expression<Func<P, bool>>>();
filters.Add(myfilter1);
filters.Add(myfilter2);
..  
Expression<Func<P, bool>> resultFilter = filters.OrTheseFiltersTogether();
IQueryable<P> query = query.Where(resultFilter);