質問

最終的に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」メソッドは指定された引数と互換性がありません。&quot;

Enumerable.OrderBy を使用して同様の方法で同様のことを正常に実行していますが、困惑しています。

ご協力いただければ幸いです。

役に立ちましたか?

解決

2番目の型としてラムダを渡す必要はありませんか?そのように。

    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)}
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top