How to write string.Contains(someText) in expression Tree

前端 未结 2 1561
离开以前
离开以前 2021-01-21 06:19

This is the tutorial I\'m following to learn Expression Tree.

I\'ve more than 35 columns to display, but the user can chose to display 10 columns at once. So one the use

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 07:10

    You are pretty close, except constructing the call of Contains does not have a right side:

    Expression col = Expression.Property(pe, columnName);
    Expression contains = Expression.Call(
        pe
    ,   typeof(string).GetMethod("Contains") // Make a static field out of this
    ,   Expression.Constant(searchText)      // Prepare a shared object before the loop
    );
    

    Once you have your call expressions, combine them with OrElse to produce the body of your lambda. You can do it with loops, or you can use LINQ:

    private static readonly MethodInfo Contains = typeof(string).GetMethod(nameof(string.Contains));
    
    public static Expression> SearchPredicate(IEnumerable properties, string searchText) {
        var param = Expression.Parameter(typeof(Student));
        var search = Expression.Constant(searchText);
        var components = properties
            .Select(propName => Expression.Call(Expression.Property(param, propName), Contains, search))
            .Cast()
            .ToList();
        // This is the part that you were missing
        var body = components
            .Skip(1)
            .Aggregate(components[0], Expression.OrElse);
        return Expression.Lambda>(body, param);
    }
    

提交回复
热议问题