LINQ动态查询类--[DynamicLinqExpressions]

时间:2022-09-30 20:51:26
 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             }