动态Linq表达式生成

动态构建 WHERE(C=>C.Id=Value):

public static IQueryable<T> WhereEqual<T>(this IQueryable<T> q, string fieldName, string fieldValue)
        {
            Type t = typeof(T);
            ParameterExpression param = Expression.Parameter(t, "c");
            Expression left = Expression.Property(param, t.GetProperty(fieldName));
            Expression right = Expression.Constant(fieldValue);
            Expression filter = Expression.Equal(left, right);
            Expression pred = Expression.Lambda(filter, param);
            Expression expr = Expression.Call(typeof(Queryable), "Where", new Type[] { t }, Expression.Constant(q), pred);
            return q.Provider.CreateQuery<T>(expr);

        }

动态构建List的Contains表达式:

        public static Expression<Func<TEntity, bool>> ContainsPredicate<TEntity, T>(T[] arr, string fieldname) where TEntity : class
        {
            ParameterExpression entity = Expression.Parameter(typeof(TEntity), "entity");
            MemberExpression member = Expression.Property(entity, fieldname);

            var containsMethods = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
            .Where(m => m.Name == "Contains");
            MethodInfo method = null;
            foreach (var m in containsMethods)
            {
                if (m.GetParameters().Count() == 2)
                {
                    method = m;
                    break;
                }
            }
            method = method.MakeGenericMethod(member.Type);
            var exprContains = Expression.Call(method, new Expression[] { Expression.Constant(arr), member });
            return Expression.Lambda<Func<TEntity, bool>>(exprContains, entity);
        }

参考地址:https://stackoverflow.com/questions/278684/how-do-i-create-an-expression-tree-to-represent-string-containsterm-in-c

感想dudu 大佬 :https://q.cnblogs.com/q/111853/

posted @ 2018-12-12 14:48  _York  阅读(587)  评论(1编辑  收藏  举报