本文介绍了在表达式< TDelegate>中为TDelegate注入参数值.并减少表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要简化表达式
Expression<Func<TQueryResult, TParam, bool>>
到
Expression<Func<TQueryResult, bool>>
通过将TParam value
作为常量插入表达式中.
by injecting TParam value
as a constant into the expression.
具体示例:
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);
}
这篇关于在表达式< TDelegate>中为TDelegate注入参数值.并减少表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!