Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Linq Expression with StartsWith, EndsWith and Contains passing a Expression<Func<T, string>>

Tags:

c#

linq

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)

like image 701
Rodrigo Caballero Avatar asked Dec 05 '11 19:12

Rodrigo Caballero


2 Answers

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);
}
like image 163
dtb Avatar answered Oct 18 '22 01:10

dtb


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);
    }
like image 27
Rodrigo Caballero Avatar answered Oct 18 '22 02:10

Rodrigo Caballero