Recursive List Flattening

后端 未结 13 1332
既然无缘
既然无缘 2020-11-27 04:25

I could probably write this myself, but the specific way I\'m trying to accomplish it is throwing me off. I\'m trying to write a generic extension method similar to the oth

13条回答
  •  抹茶落季
    2020-11-27 05:32

    Function:

    public static class MyExtentions
    {
        public static IEnumerable RecursiveSelector(this IEnumerable nodes, Func> selector)
        {
            if(nodes.Any())
                return nodes.Concat(nodes.SelectMany(selector).RecursiveSelector(selector));
    
            return nodes;
        } 
    }
    

    Usage:

    var ar = new[]
    {
        new Node
        {
            Name = "1",
            Chilren = new[]
            {
                new Node
                {
                    Name = "11",
                    Children = new[]
                    {
                        new Node
                        {
                            Name = "111",
    
                        }
                    }
                }
            }
        }
    };
    
    var flattened = ar.RecursiveSelector(x => x.Children).ToList();
    

提交回复
热议问题