如何创建表达式树以执行与"StartsWith"相同的操作

Jon*_*han 8 .net c# vb.net lambda expression-trees

目前,我有这种方法来比较两个数字

Private Function ETForGreaterThan(ByVal query As IQueryable(Of T), ByVal propertyValue As Object, ByVal propertyInfo As PropertyInfo) As IQueryable(Of T)

    Dim e As ParameterExpression = Expression.Parameter(GetType(T), "e")
    Dim m As MemberExpression = Expression.MakeMemberAccess(e, propertyInfo)
    Dim c As ConstantExpression = Expression.Constant(propertyValue, propertyValue.GetType())
    Dim b As BinaryExpression = Expression.GreaterThan(m, c)
    Dim lambda As Expression(Of Func(Of T, Boolean)) = Expression.Lambda(Of Func(Of T, Boolean))(b, e)
    Return query.Where(lambda)

End Function
Run Code Online (Sandbox Code Playgroud)

它工作正常,并以这种方式消费

query = ETForGreaterThan(query, Value, propertyInfo)
Run Code Online (Sandbox Code Playgroud)

如您所见,我给它一个IQueryable集合,并根据属性和值为它添加一个where子句.Y可以构造Lessthan,LessOrEqualThan等等System.Linq.Expressions.Expression预定义此运算符.

¿如何转换此代码以对字符串执行相同操作?System.Linq.Expressions.Expression不给我一个预定义的运算符,如"contains"或"startwith",我真的是表达树的noob.

谢谢,请在C#/ VB中发布您的答案.选择让您感觉更舒适的那个.

Tom*_*ers 19

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace WindowsFormsApplication1
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            using (var context = new NorthwindEntities())
            {
                PropertyInfo propertyInfo = typeof(Customer).GetProperty("CustomerID"); 

                IQueryable<Customer> query = context.Customers;
                query = ETForStartsWith<Customer>(query, "A", propertyInfo); 
                var list = query.ToList();
            }
        }

        static IQueryable<T> ETForStartsWith<T>(IQueryable<T> query, string propertyValue, PropertyInfo propertyInfo)
        {
            ParameterExpression e = Expression.Parameter(typeof(T), "e");
            MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
            ConstantExpression c = Expression.Constant(propertyValue, typeof(string));
            MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
            Expression call = Expression.Call(m, mi, c);

            Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(call, e); 
            return query.Where(lambda);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


fej*_*oco 5

它不是运算符,而是方法,因此您可以使用 Expression.Call() 调用它,其中 methodinfo 参数将为 typeof(string).GetMethod("StartsWith")。