动态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); }
感想dudu 大佬 :https://q.cnblogs.com/q/111853/