表达式树状态转换与选择器

时间:2013-05-10 13:45:27

标签: c# expression-trees

我有一个像

这样的实体类
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-to-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);

2 个答案:

答案 0 :(得分:1)

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

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);
    }

}

答案 1 :(得分:0)

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);

如果你想通过id进行通用选择,你必须做类似的事情;

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

这可以在你的通用存储库中找到。