码迷,mamicode.com
首页 > 其他好文 > 详细

Lambda根据属性名字选择或筛选

时间:2018-12-05 20:58:40      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:ring   access   rac   object   mpi   span   efi   nbsp   根据   

 1 using System;
 2 using System.Linq.Expressions;
 3 
 4 
 5 internal class LambdaHelper
 6 {
 7     /// <summary>
 8     /// 指定属性名字选择指定的属性
 9     /// </summary>
10     /// <typeparam name="TIn">实体类型</typeparam>
11     /// <typeparam name="TOut">属性类型</typeparam>
12     /// <param name="propertyName">属性名称</param>
13     /// <returns></returns>
14     public static Func<TIn, TOut> CreatePropertyAccessor<TIn, TOut>(string propertyName)
15     {
16         var param = Expression.Parameter(typeof(TIn));
17         var body = Expression.PropertyOrField(param, propertyName);
18         return Expression.Lambda<Func<TIn, TOut>>(body, param).Compile();
19     }
20 
21     /// <summary>
22     /// 指定属性名称和属性值对实体类进行过滤
23     /// 用法:var q = db.Where(MakeFilter("ID", 1));
24     /// </summary>
25     /// <typeparam name="EType"></typeparam>
26     /// <param name="propertyName"></param>
27     /// <param name="value"></param>
28     /// <returns></returns>
29     public static Expression<Func<EType, bool>> MakeFilter<EType>(string propertyName, object value)
30     {
31         var type = typeof(EType);
32 
33         var property = type.GetProperty(propertyName);
34 
35         var parameter = Expression.Parameter(type, "p");
36         var propertyAccess = Expression.MakeMemberAccess(parameter, property);
37         var constantValue = Expression.Constant(value);
38 
39         var equality = Expression.Equal(propertyAccess, constantValue);
40 
41         return Expression.Lambda<Func<EType, bool>>(equality, parameter);
42     }
43 
44 
45     /*用法:
46     var name1 = CreatePropertyAccessor<Obj, string>("Name");
47     var name2 = CreatePropertyAccessor<Obj, string>("Name2");
48     var name3 = CreatePropertyAccessor<Obj, string>("Name3");
49 
50     var o = new Obj() // Obj is a type with those three properties
51     {
52         Name = "foo",
53         Name2 = "bar",
54         Name3 = "baz"
55     };
56 
57     Console.WriteLine(name1(o)); // "foo"
58     Console.WriteLine(name2(o)); // "bar"
59     Console.WriteLine(name3(o)); // "baz"
60 
61     */
62 }

 

Lambda根据属性名字选择或筛选

标签:ring   access   rac   object   mpi   span   efi   nbsp   根据   

原文地址:https://www.cnblogs.com/hg533/p/10072682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!