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

Posted hg533

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lambda根据属性名字选择或筛选相关的知识,希望对你有一定的参考价值。

 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根据属性名字选择或筛选的主要内容,如果未能解决你的问题,请参考以下文章

名词筛选法识别实体类

lambda-基于谓词筛选值序列

mapgis属性筛选功能怎么用

SQLite的LIKE语句实现字符片段筛选的功能

SQLite的LIKE语句实现字符片段筛选的功能

SQLite的LIKE语句实现字符片段筛选的功能