首页 > 代码库 > Linq to sql 动态查询

Linq to sql 动态查询

辅助类

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Linq.Expressions; 5 using System.Text; 6 using System.Threading.Tasks; 7  8 namespace Drision.Framework.Logic.NYZF 9 {10     public static class PredicateBuilder11     {12         public static Expression<Func<T, bool>> True<T>() { return f => true; }13         public static Expression<Func<T, bool>> False<T>() { return f => false; }14 15         public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,16                                                             Expression<Func<T, bool>> expr2)17         {18             var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());19             return Expression.Lambda<Func<T, bool>>20                   (Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);21         }22 23         public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,24                                                              Expression<Func<T, bool>> expr2)25         {26             var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());27             return Expression.Lambda<Func<T, bool>>28                   (Expression.And(expr1.Body, invokedExpr), expr1.Parameters);29         }30     }31 }

使用方法

1                         var predicate = PredicateBuilder.False<T_Operator>();2                         foreach (var name in typenames)3                         {4                             string tmpname = name;5                             predicate = predicate.Or(o => o.OperatingRange != null && o.OperatingRange.Contains(tmpname));6                         }7                         operators = operators.AsQueryable().Where(predicate).ToList();        

 

Linq to sql 动态查询