BLOG @ MBIOQBLOG @ MBIOQ

Web 全沾(渣)工程师一枚。博客文章以 Web 和 Linux 为主,偶尔也会发发日常的样子。

c# 嵌套list 生成树状装结构以及平铺Flatten

public static IEnumerable<T> Flatten<T, R>(this IEnumerable<T> source, Func<T, R> recursion) where R : IEnumerable<T>
        {
            var flattened = source.ToList();

            var children = source.Select(recursion);

            if (children != null)
            {
                foreach (var child in children)
                {
                    flattened.AddRange(child.Flatten(recursion));
                }
            }

            return flattened;
        }

var n = new List<FamilyMember>()
                {
                    new FamilyMember { Name = "Dominic", Children = new List<FamilyMember>()
                        {
                            new FamilyMember { Name = "Brittany", Children = new List<FamilyMember>() }
                        }
                    }
                }.Flatten(x => x.Children).ToList();
本原创文章未经允许不得转载 | 当前页面:BLOG @ MBIOQ » c# 嵌套list 生成树状装结构以及平铺Flatten

评论

文章评论已关闭!