Need help creating Linq.Expression to Enumerable.GroupBy

孤街浪徒 提交于 2019-12-25 01:46:39

问题


I am attempting to generate an Expression tree that ultimately calls a series of GroupBy methods on the Enumerable type.

In simplified form I am attempting something like this:

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

The call to Expression.Call at the end throws "No method 'GroupBy' on type 'System.Linq.Enumerable' is compatible with the supplied arguments."

I am doing a similar thing, in a similar fashion with Enumerable.OrderBy successfully and am stumped.

Any help is appreciated.


回答1:


do you not need to pass a lambda in as the second type? like so.

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


来源:https://stackoverflow.com/questions/1650346/need-help-creating-linq-expression-to-enumerable-groupby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!