构造Lambda表达式

时间:2022-10-04 18:49:23
        /// <summary>
        /// 构造Lambda表达式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        private Expression<Func<T, bool>> BuildLambda<T>(int id)
        {
            ParameterExpression param = Expression.Parameter(typeof(T), "t");
            Expression left = Expression.Property(param, typeof(T).GetProperty("id"));//id为数据库的字段id.
            Expression right = Expression.Constant(id);
            Expression filter = Expression.Equal(left, right);
            var lambda = Expression.Lambda<Func<T, bool>>(filter, param);
            return lambda;
        }