C# 动态Lambda表达式
借助一个强大的Nuget 包可以很方便地解析执行Lambda表达式格式的字符串:System.Linq.Dynamic.Core
github: https://github.com/StefH/System.Linq.Dynamic.Core
// 匿名类
//匿名类
var a = new { Age = 1, Name = "小姐姐" }; Type aType = a.GetType(); var dataParameter = Expression.Parameter(aType, "data"); // 定义 data => 且data类型 var expar = DynamicExpressionParser.ParseLambda(new[] { dataParameter }, typeof(bool), "data.Age > 5 && data.Name == \"小哥哥\""); // 字段名也可以写小写(Age == age)这一点很方便 // 执行Lambda表达式 var result = cancelExpr.Compile().DynamicInvoke(a); // outPut: false; // 等同于: var result = a.Age > 5 && a.Name == "小哥哥";
public class Teach { public string Name { get; set; } public int Age { get; set; } public string AddressInfo { get; set; } }
var list = new List<Teach>(); for (int i = 0; i< 10; i++) { var tearch = new Teach { Name = "小" + i, Age = i }; list.Add(tearch); } Type type = typeof(Teach); var dataParameter = Expression.Parameter(type, "data"); var expr = DynamicExpressionParser.ParseLambda(new[] { dataParameter }, typeof(bool), "data.Age > 5 && data.Name == \"小6\""); // 或者 var expr1 = DynamicExpressionParser.ParseLambda<Teach, bool>(ParsingConfig.Default, true, "age > 5 && name == \"小6\""); var res = list.Where(t => (bool)expr.Compile().DynamicInvoke(t)).ToList(); var res2 = list.Where(expr1.Compile()).ToList();