[英]Need help creating Linq.Expression to Enumerable.GroupBy
我正在尝试生成一个表达式树,该树最终将对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'与所提供的参数都不兼容。”
我正在用Enumerable.OrderBy
以类似的方式做类似的事情,但成功并陷入了困境。
任何帮助表示赞赏。
您是否不需要通过lambda作为第二种类型? 像这样
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.