使用选择器进行表达式树条件转换

本文关键字:条件 转换 表达式 选择器 | 更新日期: 2023-09-27 18:13:05

我有一个类似的实体类

public class BookPage {
    public int PageIndex { get; set; }
}

那么我有一个表达式:

Expression<Func<int, bool>> pageIndexCondition = idx => idx == 1;

以及我想要的表达式:

Expression<Func<BookPage, bool>> pageCondition = bookPage => bookPage.PageIndex == 1;

问题是:如何使用pageIndexCondition进行LINQ到SQL查询,或者如何将pageIndexCondition转换为pageCondition

编辑:另一个不那么优雅但仍然满足我要求的解决方案是:

Expression<Func<T, bool>> GetPageIndexCondition(Expression<Func<T, int>> selector) {
     return (T item) => selector(item) < 10; // This won't work because selector is Expression, so how to implement this correctly?
}
...
var pageCondition = GetPageIndexCondition(page => page.PageIndex);

使用选择器进行表达式树条件转换

我喜欢做这些事情,尽管正如其他人所说,可能有更高效、更好的方法:

void Main()
{
    Expression<Func<int, bool>> pageIndexCondition = idx => idx == 1;
    Expression<Func<BookPage, bool>> converted = ExpressionConverter.Convert(pageIndexCondition);
}
public class ExpressionConverter : ExpressionVisitor
{
    public static Expression<Func<BookPage, bool>> Convert(Expression<Func<int, bool>> e)
    {
        var oldParameter = e.Parameters.First();
        var newParameter = Expression.Parameter(typeof(BookPage), "bp");
        Expression<Func<BookPage, int>> x = (BookPage bp) => bp.PageIndex;
        var property = ((x.Body as MemberExpression).Member as PropertyInfo);
        var memberAccess = Expression.Property(newParameter, property);
        var converter = new ExpressionConverter(oldParameter, memberAccess);
        return (Expression<Func<BookPage, bool>>)Expression.Lambda(converter.Visit(e.Body), newParameter);
    }
    private ParameterExpression pe;
    private Expression replacement;
    public ExpressionConverter(ParameterExpression pe, Expression replacement)
    {
        this.pe = pe;
        this.replacement = replacement;
    }
    protected override Expression VisitParameter(ParameterExpression node)
    {
        if(node == pe)
            return replacement;
        return base.VisitParameter(node);
    }
}
var pages = new List<BookPage>
                {
                    new BookPage { PageIndex = 1 }, 
                    new BookPage { PageIndex = 2 }
                };
Expression<Func<BookPage, bool>> pageCondition = bookPage => bookPage.PageIndex == 1;
BookPage result = pages.AsQueryable().Single(pageCondition);

如果你想要一个通用的select by id,你必须做一些类似的事情;

public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null)
{
    if (filter != null)
    {
        query = query.Where(filter);
    }
}

这将保存在您的通用存储库中。