【发布时间】:2016-02-12 00:44:53
【问题描述】:
我要为 GroupBy 构建一个动态表达式树。我想要实现的就是这样。
var NestedGrouped = listOfPerson.GroupByMany(x => x.Name,x=>x.Age).ToList();
我的 Person 类是这样的:-
class Person
{
public string Name{ get; set; }
public int Age{ get; set; }
public float Salary{ get; set; }
}
public class GroupResult
{
public object Key { get; set; }
public int Count { get; set; }
public IEnumerable Items { get; set; }
public IEnumerable<GroupResult> SubGroups { get; set; }
public override string ToString()
{ return string.Format("{0} ({1})", Key, Count); }
}
public static class MyEnumerableExtensions
{
public static IEnumerable<GroupResult> GroupByMany<TElement>(
this IEnumerable<TElement> elements,
params Func<TElement, object>[] groupSelectors)
{
if (groupSelectors.Length > 0)
{
var selector = groupSelectors.First();
//reduce the list recursively until zero
var nextSelectors = groupSelectors.Skip(1).ToArray();
return
elements.GroupBy(selector).Select(
g => new GroupResult
{
Key = g.Key,
Count = g.Count(),
Items = g,
SubGroups = g.GroupByMany(nextSelectors)
});
}
else
return null;
}
}
对于单一属性,我能够构建表达式,但我想做 GROUPBY 有多个列,如上所示。 对于单一财产:-
ParameterExpression parameter = Expression.Parameter(typeof(Person), "lambdaKey");
var menuProperty = Expression.PropertyOrField(parameter, "Name");
var lambda = Expression.Lambda<Func<Person, string>>(menuProperty, parameter);
var selector = lambda.Compile();
var result = P1.GroupByMany(selector);// P1 is list of PERSON
如何在表达式树中添加多列(例如 (x => x.Name,x=>x.Age))。
请帮忙。提前致谢。
【问题讨论】:
-
您的真正问题是什么?您的示例中没有多列,而是单列的列表(数组)。
-
@IvanStoev 我想为我可以在 GroupByMany 中传递的列列表动态生成表达式树。
-
您的示例中有 no 表达式树for list of columns。与构建单个属性的方式相同,您可以分配数组并填充每个元素,然后将数组传递给 GroupByMany。
params Func<TElement, object>[] groupSelectors是表达式数组,不是单个表达式,你同意吗?
标签: c# linq group-by expression expression-trees