c# – 在Expression中注入TDelegate的param值并减少表达式

我需要减少表达

表达式< Func< TQueryResult,TParam,bool>>

表达式< Func< TQueryResult,bool>>

通过将TParam值作为常量注入表达式中.

具体例子:

protected IQueryable<TQueryResult> AddQueryFilter<TQueryResult, TParam>(IQueryable<TQueryResult> query, Expression<Func<TQueryResult, TParam, bool>> exp,  TParam param)
{
    object obj = param;

    if (obj is string)
    {
        if (!string.IsNullOrWhiteSpace((string) obj))
        {
            var reducedExp = new Expression<Func<TQueryResult, bool>>()
            // ...
            // the magic that I need to inject param value
            //..
            return query.Where(reducedExp);
        }
    }
    else if (obj is DateTime)
    {
        //... return query.Where(reducedExp); 
    }
    else
        throw new InvalidOperationException("Param type not supported");

    return query;
}

//usage

var qr = Manager.Invoices.Query;
qr = AddQueryFilter(qr, (invoice, value) => value == invoice.Number, numberEdit.Text);
qr = AddQueryFilter(qr, (invoice, value) => value == invoice.Date, dateEdit.Date);
qr = AddQueryFilter(qr, (invoice, value) => invoice.Description.Contains(value), descEdit.Text);            

最佳答案 尝试:

protected static IQueryable<TQueryResult> AddQueryFilter<TQueryResult, TParam>(
    IQueryable<TQueryResult> query, Expression<Func<TQueryResult, TParam, bool>> exp, TParam param)
{

    var rewriter = new ExpressionRewriter();
    rewriter.Subst(exp.Parameters[1], Expression.Constant(param, typeof(TParam)));
    var body = rewriter.Apply(exp.Body);
    var lambda = Expression.Lambda<Func<TQueryResult, bool>>(body, exp.Parameters[0]);
    return query.Where(lambda);
}

使用this answer的ExpressionRewriter.

点赞