需要帮助创建Linq.Ex pression到Enumerable.GroupBy [英] Need help creating Linq.Expression to Enumerable.GroupBy
问题描述
我试图生成一个防爆pression树,最终调用了一系列可枚举类型GROUPBY方法。
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);
在最后的呼叫前pression.Call抛出没有办法GROUPBY上键入System.Linq.Enumerable与提供的参数兼容的。
The call to Expression.Call at the end throws "No method 'GroupBy' on type 'System.Linq.Enumerable' is compatible with the supplied arguments."
我做了类似的事情,以类似的方式与 Enumerable.OrderBy
成功和我难住了。
I am doing a similar thing, in a similar fashion with Enumerable.OrderBy
successfully and am stumped.
任何帮助是AP preciated。
Any help is appreciated.
推荐答案
你不需要传递一个lambda在为第二类?像这样。
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)}
}
这篇关于需要帮助创建Linq.Ex pression到Enumerable.GroupBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!