如何将 BinaryExpression 转换为 Expression<Func<T, bool>>?

Pet*_*ris 3 c# linq lambda expression entity-framework

我有以下简单的扩展类

public static class ExpressionOrExtension
{
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> source, Expression<Func<T, bool>> expression)
    {
        if (source == null)
            return expression;
        return Expression.Or(source, expression);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是 Expression.Or 返回 a BinaryExpression- 我怎样才能让它返回 anExpression<Func<T, bool>>呢?

这就是我尝试使用实体框架使用该方法的方式

    public IQueryable<BookVerse> FindByVerseReferences(string bookCode, params VerseReference[] verseReferences)
    {
        Expression<Func<BookVerse, bool>> conditions = null;
        foreach(VerseReference verseReference in verseReferences ?? new VerseReference[0])
        {
            conditions = conditions.Or<BookVerse>(x =>
                    x.BookCode == bookCode
                    && x.Chapter == verseReference.Chapter
                    && x.FirstVerse <= verseReference.LastVerse
                    && x.LastVerse >= verseReference.FirstVerse);
        }
        return MyDbContext.BookVerses.Where(conditions);
    }
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

您需要构造一个 lambda 表达式:

var p = Expression.Parameter(typeof(T));
return (Expression<Func<T,bool>>)Expression.Lambda(
    Expression.Or(
        Expression.Invoke(source, p)
    ,   Expression.Invoke(expression, p)
    )
,   p
);
Run Code Online (Sandbox Code Playgroud)

演示:

Expression<Func<int,bool>> a = x=>x > 5;
Expression<Func<int,bool>> b = x=>x < -5;
var or = Or(a, b);
var f = (Func<int,bool>)or.Compile();
for (int i = -10 ; i <= 10 ; i++) {
    Console.WriteLine("{0} - {1}", i, f(i));
}
Run Code Online (Sandbox Code Playgroud)