我想创建一个传递类型Expression<Func<T, string>
的表达式的方法来创建类型Expression<Func<T, bool>>
的表达式,以使用StartsWith
,EndsWith
和{{过滤字符串属性1}}类似这些表达式的方法:
Contains
该方法应如下所示:
.Where(e => e.MiProperty.ToUpper().StartsWith("ABC"));
.Where(e => e.MiProperty.ToUpper().EndsWith("XYZ"));
.Where(e => e.MiProperty.ToUpper().Contains("MNO"));
其中FilterType是包含上述三个操作的枚举类型(public Expression<Func<T, bool>> AddFilterToStringProperty<T>(Expresssion<Func<T, string>> pMyExpression, string pFilter, FilterType pFiltertype)
,StartsWith
,EndsWith
)
答案 0 :(得分:7)
试试这个:
public static Expression<Func<T, bool>> AddFilterToStringProperty<T>(
Expression<Func<T, string>> expression, string filter, FilterType type)
{
return Expression.Lambda<Func<T, bool>>(
Expression.Call(
expression.Body,
type.ToString(),
null,
Expression.Constant(filter)),
expression.Parameters);
}
答案 1 :(得分:4)
谢谢@dtb。它工作正常,我添加了一个&#34; not null&#34;这种情况的表达式如下:
public static Expression<Func<T, bool>> AddFilterToStringProperty2<T>(
Expression<Func<T, string>> expression, string filter, FilterType type)
{
var vNotNullExpresion = Expression.NotEqual(
expression.Body,
Expression.Constant(null));
var vMethodExpresion = Expression.Call(
expression.Body,
type.ToString(),
null,
Expression.Constant(filter));
var vFilterExpresion = Expression.AndAlso(vNotNullExpresion, vMethodExpresion);
return Expression.Lambda<Func<T, bool>>(
vFilterExpresion,
expression.Parameters);
}