动态LINQ嵌套组 [英] Dynamic linq nested group

查看:33
本文介绍了动态LINQ嵌套组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进行动态嵌套组?

让我说我有这个例子:

result.GroupBy(f => f.level1)
              .Select(l1 => new {
                  name = l1.Key,
                  children = l1.GroupBy(l2 => l2.level2)
                    .Select(l2 => new {
                        name = l2.Key,
                        children = l2.GroupBy(l3 => l3.level3)
                            .Select(l3 => new {
                                name = l3.Key,
                                children = new someObject()
                  });

如何更改此参数以按参数动态分组.从更深处开始,然后继续.

How can i change this to do group dynamically by parameter. Start from deeper and go on.

推荐答案

如果您想真正地动态嵌套它,我不会将级别名称存储为属性在您的Level Object中,而是将它们放在数组中可以以某种方式遍历它们.

If you want to truly dynamically nest this, I would not store the level names as properties in your Level Object, rather I would put them in an array so you can loop through them in some fashion.

话虽如此,您可以构建一个通用的 NestedGroupBy<> Linq扩展方法,该方法可以处理您要执行的操作,您只需要为每个级别传递一个lambda:

Having said that, you can build a general NestedGroupBy<> Linq extension method which can handle what you want to do, you just need to pass a lambda for each level you want:

// The NestedGroupBy<> extension method
public static class LinqExtensions
{
    public static IEnumerable<TTarget> NestedGroupBy<TSource, TTarget, TKey>(this IEnumerable<TSource> source, Func<TKey, IEnumerable<TTarget>, TTarget> factory, params Func<TSource, TKey>[] keySelectors)
    {
        return source.NestedGroupBy(factory, keySelectors, 0);
    }

    private static IEnumerable<TTarget> NestedGroupBy<TSource, TTarget, TKey>(this IEnumerable<TSource> source, Func<TKey, IEnumerable<TTarget>, TTarget> factory, Func<TSource, TKey>[] keySelectors, int selectorIndex)
    {
        // reached the end, just return an empty list
        if(selectorIndex >= keySelectors.Length)
        {
            return new List<TTarget>();
        }

        // do the GroupBy using the function at index selectorIndex in our list to find the key (level name)
        // then call the factory to construct the target SomeObject, passing it the key and the recursive call to NestedGroupBy<>
        return source.GroupBy(keySelectors[selectorIndex])
            .Select(f => factory(
                f.Key,
                f.NestedGroupBy(factory, keySelectors, selectorIndex + 1)
            )
        );
    }
}

// source object - assuming your result variable is List<LevelObject>
public class LevelObject
{
    public string level1 {get;set;}
    public string level2 {get;set;}
    public string level3 {get;set;}

    public LevelObject(string level1, string level2, string level3)
    {
        this.level1 = level1;
        this.level2 = level2;
        this.level3 = level3;
    }
}

// target object - what we will end up with in our final list
// the constructor is optional - it just makes the NestedGroupBy<> call cleaner.
public class SomeObject
{
    public string name {get; set;}
    public IEnumerable<SomeObject> children {get; set;}

    public SomeObject(string name, IEnumerable<SomeObject> children)
    {
        this.name = name;
        this.children = children;
    }
}

// Sample code to use it. The JToken/JsonConvert call at the end just pretty prints the result on screen.
public static void Main()
{
    List<LevelObject> result = new List<LevelObject>()
    {
        new LevelObject("L1a1", "L2a1", "L3a1"),
        new LevelObject("L1a1", "L2a2", "L3a1"),
        new LevelObject("L1a1", "L2a1", "L3a2"),
        new LevelObject("L1b1", "L2b1", "L3b1"),
        new LevelObject("L1c1", "L2c1", "L3c1")
    };

    /* old way - produces same result
            var groupings = result.GroupBy(f => f.level1)
                  .Select(l1 => new SomeObject {
                      name = l1.Key,
                      children = l1.GroupBy(l2 => l2.level2)
                        .Select(l2 => new SomeObject{
                            name = l2.Key,
                            children = l2.GroupBy(l3 => l3.level3)
                                .Select(l3 => new SomeObject{
                                    name = l3.Key,
                                    children = new List<SomeObject>()
                                })})}).ToList();
    */

    var groupings = result.NestedGroupBy<LevelObject, SomeObject, string>(
        (key, children) => new SomeObject(key, children),
        l => l.level1, l => l.level2, l => l.level3
    ).ToList();

    Console.WriteLine(groupings.GetType());

    Console.WriteLine(JToken.Parse(JsonConvert.SerializeObject(groupings)));
}

这篇关于动态LINQ嵌套组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆