How to flatten tree via LINQ?

后端 未结 14 2548
抹茶落季
抹茶落季 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:38

    Below is Ivan Stoev's code with the additonal feature of telling the index of every object in the path. E.g. search for "Item_120":

    Item_0--Item_00
            Item_01
    
    Item_1--Item_10
            Item_11
            Item_12--Item_120
    

    would return the item and an int array [1,2,0]. Obviously, nesting level is also available, as length of the array.

    public static IEnumerable<(T, int[])> Expand(this IEnumerable source, Func> getChildren) {
        var stack = new Stack>();
        var e = source.GetEnumerator();
        List indexes = new List() { -1 };
        try {
            while (true) {
                while (e.MoveNext()) {
                    var item = e.Current;
                    indexes[stack.Count]++;
                    yield return (item, indexes.Take(stack.Count + 1).ToArray());
                    var elements = getChildren(item);
                    if (elements == null) continue;
                    stack.Push(e);
                    e = elements.GetEnumerator();
                    if (indexes.Count == stack.Count)
                        indexes.Add(-1);
                    }
                if (stack.Count == 0) break;
                e.Dispose();
                indexes[stack.Count] = -1;
                e = stack.Pop();
            }
        } finally {
            e.Dispose();
            while (stack.Count != 0) stack.Pop().Dispose();
        }
    }
    

提交回复
热议问题