c# 拼接lambda表达式
Posted dcy521
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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表达式的主要内容,如果未能解决你的问题,请参考以下文章