How to flatten tree via LINQ?

后端 未结 14 2202
抹茶落季
抹茶落季 2020-11-22 04:56

So I have simple tree:

class MyNode
{
 public MyNode Parent;
 public IEnumerable Elements;
 int group = 1;
}

I have a I

14条回答
  •  悲哀的现实
    2020-11-22 05:46

    Combining Dave's and Ivan Stoev's answer in case you need the level of nesting and the list flattened "in order" and not reversed like in the answer given by Konamiman.

     public static class HierarchicalEnumerableUtils
        {
            private static IEnumerable> ToLeveled(this IEnumerable source, int level)
            {
                if (source == null)
                {
                    return null;
                }
                else
                {
                    return source.Select(item => new Tuple(item, level));
                }
            }
    
            public static IEnumerable> FlattenWithLevel(this IEnumerable source, Func> elementSelector)
            {
                var stack = new Stack>>();
                var leveledSource = source.ToLeveled(0);
                var e = leveledSource.GetEnumerator();
                try
                {
                    while (true)
                    {
                        while (e.MoveNext())
                        {
                            var item = e.Current;
                            yield return item;
                            var elements = elementSelector(item.Item1).ToLeveled(item.Item2 + 1);
                            if (elements == null) continue;
                            stack.Push(e);
                            e = elements.GetEnumerator();
                        }
                        if (stack.Count == 0) break;
                        e.Dispose();
                        e = stack.Pop();
                    }
                }
                finally
                {
                    e.Dispose();
                    while (stack.Count != 0) stack.Pop().Dispose();
                }
            }
        }
    

提交回复
热议问题