码迷,mamicode.com
首页 > Windows程序 > 详细

c# 拼接lambda表达式

时间:2019-09-05 18:35:56      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:turn   stat   res   bsp   dex   表达   compile   拼接   金刚   

添加一个类:

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表达式

标签:turn   stat   res   bsp   dex   表达   compile   拼接   金刚   

原文地址:https://www.cnblogs.com/dcy521/p/11468768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!