【发布时间】:2014-05-28 02:38:05
【问题描述】:
我正在尝试使用表达式树来构建一对嵌套的组,并且完全被 Select 及其对参数的期望所困扰。我最终想要做的是通过表达式树来构建它;
var queryNestedGroups = products.GroupBy(x => x.Category)
.Select(p => new
{
key = p.Key,
objects = p.ToList().GroupBy(y => y.Subcategory)
.Select(y => new { key = y.Key, objects = y.ToList() })
})
.AsQueryable();
这是我目前的尝试(产品是一个列表);
var data = Expression.Constant(products);
var arg = Expression.Parameter(typeof(Product), "arg");
var nameProperty = Expression.PropertyOrField(arg, "Category");
var groupByLambda = Expression.Lambda<Func<Product, string>>(nameProperty, arg);
var groupByExpression = Expression.Call(
typeof(Queryable),
"GroupBy",
new Type[] { typeof(Product), typeof(string) },
data,
groupByLambda);
var parameterExp = Expression.Parameter(typeof(IGrouping<string, Product>), "p");
var keyProp = Expression.PropertyOrField(parameterExp, "Key");
ConstructorInfo constructorInfo = typeof(object)
.GetConstructor(new[] { typeof(string), typeof(Product) });
Type anonymousResultType = new { Key = "abc", Values = new List<Product>() }.GetType();
var exp = Expression.New(
anonymousResultType.GetConstructor(new[] { typeof(string), typeof(List<Product>) }),
Expression.Constant("def"),
Expression.Constant(new List<Product>()));
var selectLambda = Expression.Lambda(exp);
var selectExpression = Expression.Call(
typeof(Queryable),
"Select",
new Type[] { typeof(List<Product>), selectLambda.Body.Type },
data,
selectLambda);
var finalExpression = Expression.Lambda(groupByExpression);
一切进展顺利,除了我在 var selectExpression = ... 上遇到异常,告诉我我的类型参数和参数错误。不幸的是,它没有告诉我哪些参数以及它们错误的原因。我已经尝试了我能想到的所有排列。所以有两个问题;
我怎么知道是什么
- 正是它想要的类型?
- 在这种情况下,正确的类型/参数是什么?
【问题讨论】:
标签: c# .net linq linq-to-objects expression-trees