NET 构建动态Lambda表达式
1.定义lambda的参数,型如我们常写的“x=>”: using System.Linq.Expressions;
var type = typeof(CustClass); ParameterExpression parameter = Expression.Parameter(type, "x");
2.定义要使用lambda的属性成员(比如添加时间: Name)
MemberExpression member = Expression.PropertyOrField(parameter, "Name");
3.转换为Expression表达式 x => x.Name
dynamic exprelambda = Expression.Lambda(member, parameter);
4.转换为Expression表达式 x => x.Name.Constant("张三")
// 表达式左侧 x.Name var left = Expression.PropertyOrField(parameter, "Name"); // 表达式右侧 '张三' var right = Expression.Constant("张三"); // 表达式连接符 Equals var constant = Expression.Equal(left, right); // 转换成完整表达式: x => x.Name.Equals("张三") var exprelambda = Expression.Lambda<Func<CustClass, bool>>(constant, parameter);
5.将Expression表达式转换为Func委托,用于Where里面的参数
var lambda = exprelambda.Compile();
6.调用
var list = new List<CustClass>(); var sortList = list.OrderBy(x => lambda(x));
7.完整Demo
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class TestLambda : BaseTesting { public TestLambda(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } [Fact] public void Run() { var list = new List<CustClass>(); Enumerable.Range(0, 10).ToList().ForEach(x => list.Add(new CustClass { Code = x, Name = $"张三-{x}", })); var type = typeof(CustClass); // 1.定义lambda的参数,型如我们常写的“x=>”: using System.Linq.Expressions; ParameterExpression parameter = Expression.Parameter(type, "x"); { // 2.定义要使用lambda的属性成员(比如添加时间: Name) MemberExpression member = Expression.PropertyOrField(parameter, "Name"); // 3.转换为Expression表达式 x => x.Name dynamic exprelambda = Expression.Lambda(member, parameter); // 5.将Expression表达式转换为Func委托,用于Where里面的参数 var lambda = exprelambda.Compile(); // 6.调用 var sortList = list.OrderBy(x => lambda(x)); var sortDescList = list.OrderByDescending(x => lambda(x)); } { // 表达式左侧 x.Name var left = Expression.PropertyOrField(parameter, "Name"); // 表达式右侧 '张三' var right = Expression.Constant("张三-0"); // 表达式连接符 == var constant = Expression.Equal(left, right); // 3.转换成完整表达式: x => x.Name.Equals("张三") var exprelambda = Expression.Lambda<Func<CustClass, bool>>(constant, parameter); // 5.将Expression表达式转换为Func委托,用于Where里面的参数 var lambda = exprelambda.Compile(); // 6.调用 var whereList = list.Where(x => lambda(x)).ToList(); } } } public class CustClass { public int Code { get; set; } public string Name { get; set; } }