使用动态生成的Lambda作为Linq OrderBy的输入

时间:2014-06-11 22:35:47

标签: c# linq sorting lambda

我想以编程方式创建Linq OrderBy子句。所以我试图动态创建Lambdas并将它们用作我的OrderBy子句的输入,但它不起作用。不确定OrderBy的实际输入是什么。

我在这里缺少什么?

    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();
    }

1 个答案:

答案 0 :(得分:1)

刚刚找到答案。 Lambda表达式必须是Func

类型
var lambdaExpr = Expression.Lambda<Func<Person, object>>(prop, new List<ParameterExpression>() { paramExpr });

然后一切正常!