views:

377

answers:

1

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  A: 

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)}
    }
Hath
that worked. thank you
dkackman