How to create an Expression tree to do the same as “StartsWith”

前端 未结 2 1131
青春惊慌失措
青春惊慌失措 2021-01-02 04:04

Currently, I have this method to compare two numbers

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


        
2条回答
  •  情深已故
    2021-01-02 05:02

    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 query = context.Customers;
                    query = ETForStartsWith(query, "A", propertyInfo); 
                    var list = query.ToList();
                }
            }
    
            static IQueryable ETForStartsWith(IQueryable 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> lambda = Expression.Lambda>(call, e); 
                return query.Where(lambda);
            }
        }
    }
    

提交回复
热议问题