需要帮助创建Linq.Expression到Enumerable.GroupBy

时间:2009-10-30 15:03:51

标签: c# linq .net-3.5 linq-to-objects expression

我正在尝试生成一个表达式树,最终在Enumerable类型上调用一系列GroupBy方法。

我以简化的形式尝试这样的事情:

IEnumerable<Data> list = new List<Data>{new Data{Name = "A", Age=10},
   new Data{Name = "A", Age=12},
   new Data{Name = "B", Age=20},
   new Data{Name="C", Age=15}};

Expression data = Expression.Parameter(typeof(IEnumerable<Data>), "data");
Expression arg = Expression.Parameter(typeof(Data), "arg");
Expression nameProperty = Expression.PropertyOrField(arg, "Name");

Expression group = Expression.Call(typeof(Enumerable), "GroupBy", new Type[] { typeof(Data), typeof(string) }, data, nameProperty);

最后对Expression.Call的调用抛出“类型'System.Linq.Enumerable'上的无方法'GroupBy'与提供的参数兼容。”

我正在做类似的事情,以类似的方式与Enumerable.OrderBy成功并且难倒。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你不需要传递lambda作为第二种类型吗?像这样。

    public void Test()
    {
        IEnumerable<Data> list = new List<Data>
        {
            new Data{Name = "A", Age=10},
            new Data{Name = "A", Age=12},
            new Data{Name = "B", Age=20},
            new Data{Name= "C", Age=15}
        };


        var data = Expression.Parameter(typeof(IEnumerable<Data>), "data");
        var arg = Expression.Parameter(typeof(Data), "arg");
        var nameProperty = Expression.PropertyOrField(arg, "Name");
        var lambda = Expression.Lambda<Func<Data, string>>(nameProperty, arg);

        var expression = Expression.Call(
            typeof(Enumerable),
            "GroupBy", 
            new Type[] { typeof(Data), typeof(string) },
            data,
            lambda);

        //expected = {data.GroupBy(arg => arg.Name)}
    }