【发布时间】:2014-02-05 13:03:13
【问题描述】:
首先,我想让您知道,在制作这个问题之前,我已经搜索了其他问题和答案,但我找不到任何可以帮助我解决我所面临的具体问题的问题。
我需要根据其类的两个属性过滤寄存器,其中一个是与搜索对应的字段,另一个是数据库中必须引用寄存器的另一个实体的数字代码。
我的搜索功能有以下签名:
public List<TView> SearchByField(int parentCode, string fieldName, string filter);
我尝试使用表达式树来实现这一点,并得到了两个表达式,但现在我没有得到组合这些表达式来构建一个传递给最终的表达式
Expression.AndAlso(parentCodeFilterExpression, textFilterExpression);
这会将too表达式组合在一个中。
到目前为止,我得到的是下面显示的代码(抱歉,sn-p 太长了,但我认为这是使问题更容易理解的必要条件):
public List<TView> SearchPerField(int parentCode, string fieldName, string filter)
{
var lambdaExpression = GetLambdaExpressionForSearchByField(fieldName, filter, parentCode);
return new PersistenciaImpl<TView>().Where(lambdaExpression).ToList();
}
private Expression<Func<TView, bool>> GetLambdaExpressionForSearchByField(string fieldName, string filter, int parentCode)
{
Expression<Func<TView, bool>> textFilterExpression = GetTextFilterExpression(fieldName, filter);
Expression<Func<TView, bool>> parentCodeFilterExpression = GetParentCodeFilterExpression(parentCode);
Expression.Lambda<Func<TView, bool>>(textFilterExpression, parentCodeFilterExpression);
// THIS IS THE POINT. HOW TO MAKE THIS WORK?
Expression.AndAlso(parentCodeFilterExpression, textFilterExpression);
return textFilterExpression;
}
private Expression<Func<TView, bool>> GetParentCodeFilterExpression(int parentCode)
{
ParameterExpression parameter = Expression.Parameter(typeof(TView), "x");
Expression parent = Expression.Property(parameter, "Parent");
Expression parentCodeExpression = Expression.Property(parent, "Code");
Expression target = Expression.Constant(parentCode);
Expression containsMethod = Expression.Call(parentCodeExpression, "Equals", null, target);
Expression<Func<TView, bool>> textFilterExpression =
Expression.Lambda<Func<TView, bool>>(containsMethod, parameter);
return textFilterExpression;
}
private Expression<Func<TView, bool>> GetTextFilterExpression(string fieldName, string filter)
{
ParameterExpression parameter = Expression.Parameter(typeof(TView), "x");
Expression property = Expression.Property(parameter, fieldName);
Expression target = Expression.Constant(filter.ToUpper());
Expression containsMethod = Expression.Call(property, "Contains", null, target);
Expression<Func<TView, bool>> textFilterExpression =
Expression.Lambda<Func<TView, bool>>(containsMethod, parameter);
return textFilterExpression;
}
感谢您的任何建议。
【问题讨论】:
标签: c# lambda expression-trees