构造Lambda表达式

时间:2021-10-17 02:55:35
        /// <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;
        }