假设数据库有Teacher表,Student表,用orm生成实体后,我又自定义了一个Person类,三个类都有Age属性,能否实现一个方法,入参是
Expression<Func<Person, bool>> pre=u=>Age>20;
从而筛选出Age大于20的Teacher和Student。
—- 20分
可以,用MakeMemberAccess创建表达式树。
需要详细代码请先结贴。
—-
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class A { public int Age { get; set; } } class Program { static void Main(string[] args) { var exp = buildExp<A>(20); Console.WriteLine(exp); Console.WriteLine(exp.Compile()(new A() { Age = 17 })); } static Expression<Func<T, bool>> buildExp<T>(int age) { var p = Expression.Parameter(typeof(T), "x"); var c = Expression.Constant(age, typeof(int)); var m = Expression.MakeMemberAccess(p, typeof(T).GetMember("Age")[0]); var l = Expression.Lambda<Func<T, bool>>(Expression.GreaterThan(m, c), p); return l; } } }
x => (x.Age > 20)
False
Press any key to continue . . .