LINQ动态查询类--[DynamicLinqExpressions]

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Linq.Expressions;
 6 
 7 namespace Test
 8 {
 9     /// <summary>
10     /// 一個老外寫的擴充Expression方法的靜態類別,可以解決上面冗長的程式碼
11     /// </summary>
12     public static class DynamicLinqExpressions//注意static靜態型別
13     {
14         public static Expression<Func<T, bool>> True<T>() { return f => true; }
15         public static Expression<Func<T, bool>> False<T>() { return f => false; }
16 
17         //注意this
18         public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
19                                                             Expression<Func<T, bool>> expr2)
20         {
21             var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
22             return Expression.Lambda<Func<T, bool>>
23                   (Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
24         }
25 
26         public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
27                                                              Expression<Func<T, bool>> expr2)
28         {
29             var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
30             return Expression.Lambda<Func<T, bool>>
31                   (Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
32         }
33     }
34 }

使用示例:

1 SchoolContainer school = new SchoolContainer();
2             var eps = DynamicLinqExpressions.True<Teacher>();
3             eps.And(T=>T.Name.Contains("1"));
4             var ss = school.Teacher.Where(T => T.Name.Contains("PM")).Where(eps);
5             foreach (var item in ss)
6             {
7                 Console.WriteLine(item.Name);
8             }

 

转载于:https://www.cnblogs.com/lyghost/p/3338393.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值