Lambda根據屬性名字選擇或篩選
阿新 • • 發佈:2018-12-05
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); 18return 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 }