[英]Need help creating Linq.Expression to Enumerable.GroupBy
I am attempting to generate an Expression tree that ultimately calls a series of GroupBy methods on the Enumerable type. 我正在尝试生成一个表达式树,该树最终将对Enumerable类型调用一系列GroupBy方法。
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." 最后,对Expression.Call的调用将引发“类型'System.Linq.Enumerable'上的任何方法'GroupBy'与所提供的参数都不兼容。”
I am doing a similar thing, in a similar fashion with Enumerable.OrderBy
successfully and am stumped. 我正在用Enumerable.OrderBy
以类似的方式做类似的事情,但成功并陷入了困境。
Any help is appreciated. 任何帮助表示赞赏。
do you not need to pass a lambda in as the second type? 您是否不需要通过lambda作为第二种类型? 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)}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.