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 PredicateBuilder
11     {
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();        

 

posted @ 2017-05-03 16:15  彭满意  阅读(319)  评论(0编辑  收藏  举报