I want to create a method passing a expression of type Expression<Func<T, string>
to create expression of type Expression<Func<T, bool>>
to filter a string property with the StartsWith
, EndsWith
and Contains
methods like these expressions:
.Where(e => e.MiProperty.ToUpper().StartsWith("ABC"));
.Where(e => e.MiProperty.ToUpper().EndsWith("XYZ"));
.Where(e => e.MiProperty.ToUpper().Contains("MNO"));
the method should look like:
public Expression<Func<T, bool>> AddFilterToStringProperty<T>(Expresssion<Func<T, string>> pMyExpression, string pFilter, FilterType pFiltertype)
where FilterType is an enum type that contains the three of the mentioned operations (StartsWith
, EndsWith
, Contains
)
Try this:
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);
}
Thanks @dtb. It works fine and I added a "not null" expression for this case like this:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With