var a = new ParameterExpression { Type = typeof(Article), IsByRef = false, Name = "a" };
new Expression<Func<Article, bool>> { NodeType = ExpressionType.Lambda, Type = typeof(Func<Article, bool>), Parameters = new ReadOnlyCollection<ParameterExpression> { a }, Body = new BinaryExpression { NodeType = ExpressionType.GreaterThan, Type = typeof(bool), Left = new MemberExpression { Type = typeof(int), Expression = a, Member = typeof(Article).GetProperty("Id") }, Right = new ConstantExpression { Type = typeof(int), Value = 5 } }, ReturnType = typeof(bool) }
// using static System.Linq.Expressions.Expression
var a = Parameter( typeof(Article), "a" );
Lambda( GreaterThan( MakeMemberAccess(a, typeof(Article).GetProperty("Id") ), Constant(5) ), a )
只需将它粘贴到代码中稍作修改即可:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
static void Main(string[] args) { Console.WriteLine("请输入 1:小于,2:大于"); string s = Console.ReadLine(); var a = Parameter(typeof(Article),"a" ); BinaryExpression binaryCompare; if (s == "1") { binaryCompare = LessThan(MakeMemberAccess(a,typeof(Article).GetProperty("Id")), Constant(5)); }else { binaryCompare = GreaterThan(MakeMemberAccess(a, typeof(Article).GetProperty("Id")), Constant(5)); } var expr = Lambda<Func<Article,bool>>(binaryCompare, a); using(var ctx = new MyDbContext()) { ctx.Articles.Where(expr).ToArray(); } }
动态构建表达式树代码举例
修改Article类,override ToString方法:
1 2 3 4 5 6 7 8 9 10 11
public class Article { public int Id { get; set; } public string Title { get; set; } public string Message { get; set; } public List<Comment> Comments = new List<Comment>();//实体类中关系属性 public bool IsDeleted { get; set; } public override string ToString() { return $"ID:{Id},Title:{Title},Message:{Message}"; } }
using System.Linq.Dynamic.Core; namespace Interview { internal class Program { static void Main(string[] args) { using(var ctx = new MyDbContext()) { var res = ctx.Articles.Where("Id>=5").Select("new(Id,Title)").ToDynamicArray(); foreach(var item in res) { Console.WriteLine(item.Id+","+item.Title); } } } } }