• 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);
            }
  • 相关阅读:
    Js~数组的操作push,pop,shift,unshift
    SqlServer 字段类型详解
    数据库设计三大范式
    HTML 解析类库HtmlAgilityPack
    设计模式六大原则
    表达式目录树
    在Web.config或App.config中的添加自定义配置
    史上最全 ——LINQ to SQL语句
    C# 加密解密类
    WebService登陆验证四种方式
  • 原文地址:https://www.cnblogs.com/dcy521/p/11468768.html
Copyright © 2020-2023  润新知