IQueryable.Where() suitable Expression in where?

后端 未结 4 1263
自闭症患者
自闭症患者 2021-01-03 02:05

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;
..
S         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 02:57

    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> OrTheseFiltersTogether( 
      this IEnumerable>> filters) 
    { 
        Expression> firstFilter = filters.FirstOrDefault(); 
        if (firstFilter == null) 
        { 
            Expression> 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> result = Expression.Lambda>(body, param); 
        return result; 
    } 
    

    Then later:

    Expression> myFilter1 = x => foo1 == true && foo2 == false;  
    Expression> myFilter2 = x => ... ;  
    ..  
    List>> filters = new List>>();
    filters.Add(myfilter1);
    filters.Add(myfilter2);
    ..  
    Expression> resultFilter = filters.OrTheseFiltersTogether();
    IQueryable

    query = query.Where(resultFilter);

提交回复
热议问题