使用动态生成的Lambda作为Linq order的输入
本文关键字:作为 Linq order 输入 Lambda 动态 | 更新日期: 2023-09-27 18:08:18
我想以编程方式创建Linq order子句。因此,我尝试动态创建Lambdas并将它们用作OrderBy子句的输入,但它不起作用。不确定order的实际输入是什么
我在这里错过了什么?
static void Main(string[] args)
{
List<Person> people = new List<Person>();
people.Add(new Person { Age = 10, Name = "D" });
people.Add(new Person { Age = 20, Name = "C" });
people.Add(new Person { Age = 30, Name = "B" });
people.Add(new Person { Age = 40, Name = "A" });
var paramExpr = Expression.Parameter(typeof(Person), "p");
var prop = Expression.Property(paramExpr, "Name");
var lambdaExpr = Expression.Lambda(prop, new List<ParameterExpression>() { paramExpr });
Console.WriteLine(lambdaExpr); //Outputs p => p.Name
var sortedPeople = people.OrderBy(lambdaExpr.Compile()); //This doesn't work.
//var sortedPeople = people.OrderBy(p => p.Name); //This works
foreach (var person in sortedPeople)
{
Console.WriteLine(String.Format("{0} - {1}", person.Name, person.Age));
}
Console.ReadKey();
}
刚刚找到答案。Lambda表达式的类型必须是Func
var lambdaExpr = Expression.Lambda<Func<Person, object>>(prop, new List<ParameterExpression>() { paramExpr });
那么一切都成功了!