Performance of nested yield in a tree

前端 未结 5 595
既然无缘
既然无缘 2020-11-28 12:20

I\'ve got a tree-like structure. Each element in this structure should be able to return a Enumerable of all elements it is root to. Let\'s call this method IEnumerabl

5条回答
  •  一向
    一向 (楼主)
    2020-11-28 12:57

    A better solution might be to create a visit method that recursively traverses the tree, and use that to collect items up.

    Something like this (assuming a binary tree):

    public class Node
    {
        public void Visit(Action action)
        {
            action(this);
            left.Visit(action);
            right.Visit(action);
        }
    
        public IEnumerable GetAll ()
        {
            var result = new List();
            Visit( n => result.Add(n));
            return result;
        }
    }
    

    Taking this approach

    • Avoids creating large numbers of nested iterators
    • Avoids creating any more lists than necessary
    • Is relatively efficient
    • Falls down if you only need part of the list regularly

提交回复
热议问题