Create a Linq expression using StartsWith, EndsWith and Contains the transmission of the expression <Func <T, string >>
I want to create a method that passes an expression of type Expression<Func<T, string> to create an expression of type Expression<Func<T, bool>> to filter the property of a string using the StartsWith , EndsWith and Contains methods similar to 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 this:
public Expression<Func<T, bool>> AddFilterToStringProperty<T>(Expresssion<Func<T, string>> pMyExpression, string pFilter, FilterType pFiltertype) where FilterType is an enumeration type that contains three of the mentioned operations ( StartsWith , EndsWith , Contains )
+8
Rodrigo caballero
source share2 answers
Try the following:
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); } +7
dtb
source shareThanks @dtb. It works fine, and I added the expression "not null" for this case:
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); } +4
Rodrigo caballero
source share