繁体   English   中英

具有多个属性的动态GroupBy选择器表达式树的构建

[英]Building Dynamic GroupBy Selector Expression Tree With Multiple Properties

我要为GroupBy构建动态的表达式树。 我想要实现的就是这样。

var NestedGrouped = listOfPerson.GroupByMany(x => x.Name,x=>x.Age).ToList(); 

我的人物课堂就像:-

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;
        }
    }

对于Single Property,我能够构建表达式,但我想对多列进行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))。
请帮忙。 提前致谢。

GroupByMany()接受一组委托,每个键一个委托。 因此,您需要为每个键创建并编译一个单独的表达式。

该代码可能类似于:

private static Func<TElement, object> CreateSelector<TElement>(string key)
{
    var parameter = Expression.Parameter(typeof(TElement), "lambdaKey");
    var property = Expression.PropertyOrField(parameter, key);
    var lambda = Expression.Lambda<Func<TElement, string>>(property, parameter);
    return lambda.Compile();
}

public static IEnumerable<GroupResult> GroupByMany<TElement>(
    this IEnumerable<TElement> elements,
    params string[] groupKeys)
{
    return elements.GroupByMany(groupKeys.Select(CreateSelector<TElement>).ToArray());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM