[英]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.