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

前端 未结 2 1113
青春惊慌失措
青春惊慌失措 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 04:46

    It's not an operator, but a method, so you can call it with Expression.Call(), where the methodinfo parameter will be typeof(string).GetMethod("StartsWith").

    0 讨论(0)
  • 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<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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题