c# 拼接lambda表达式

添加一个类:

public static class PredicateExtensions
    {
        public static Expression<Func<T, bool>> True<T>()
        {
            return f => true;
        }

        public static Expression<Func<T, bool>> False<T>()
        {
            return f => false;
        }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
        {
            var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>(Expression.Or(expression1.Body, invokedExpression), expression1.Parameters);
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
        {
            var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>(Expression.And(expression1.Body, invokedExpression), expression1.Parameters);
        }
    }

使用方法:

public ActionResult Index(string keyword)
        {
            string name = "变形金刚";

            decimal price = 20000;

            DateTime dt = Convert.ToDateTime("2019 - 09 - 09");

            Expression<Func<Movies, bool>> expression = t => true;

            expression = expression.And(t => t.MName == name);

            expression = expression.And(t => t.MPrice == price);

            expression = expression.And(t => t.ShowTime == dt);

            var ds = db.Movies.Where(expression.Compile()).AsQueryable().ToList();

            return View(ds);
        }

 

c# 拼接lambda表达式

上一篇:Acwing-102-最佳牛围栏(二分,实数)


下一篇:二、yargs用法 - yargs API