Domanda

Sto tentando di generare un albero di espressioni che alla fine chiama una serie di metodi GroupBy sul tipo Enumerable.

In forma semplificata sto tentando qualcosa del genere:

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

La chiamata a Expression.Call alla fine genera " Nessun metodo 'GroupBy' sul tipo 'System.Linq.Enumerable' è compatibile con gli argomenti forniti. "

Sto facendo una cosa simile, in modo simile con Enumerable.OrderBy con successo e sono sconcertato.

Qualsiasi aiuto è apprezzato.

È stato utile?

Soluzione

non è necessario passare un lambda come secondo tipo? così.

    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)}
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top