C# 中用 yield return 關鍵字實現擷取樹型資料結構的所有子節點

來源:互聯網
上載者:User

通常,我們在擷取樹形結構資料所有子節點時,需要寫一個遞迴調用的方法,迴圈調用,這是資料結構演算法裡的通用寫法。

下面介紹用 yield return是怎麼做的。如:

public class TreeNodeInfo

{

    public string Name { get; set; } 

    public List<TreeNodeInfo> Children { get; set; }

}

 

擷取所有子節點:

private IEnumerable<TreeNodeInfo> GetAllChildren(TreeNodeInfo root)

{

    Queue<TreeNodeInfo> queue = new Queue<TreeNodeInfo>(root.Children);

    while (queue.Count > 0)

    {

        TreeNodeInfo node = queue.Dequeue();

        yield return node;

        if (node.Children != null && node.Children.Count > 0)

        {

            node.Children.ForEach(o =>

            {

                queue.Enqueue(o);

            });

        }

    }

}

 

這僅僅是寫法的不同,如果用遞迴方法,運行時會幫我們處理回調方法的堆棧。而用 yield return 我們需要自己維護迴圈隊列。

 yield return 的另一個好處是,當你調用 GetAllChildren 方法時,程式並沒有真正的運行方法體,只有你在對傳回值進行操作時,才運行方法體,這個特性在某些情境很有用。如對結果進行 foreach 操作:

 

IEnumerable<TreeNodeInfo> nodes = this.GetAllChildren(this.rootNode);       

foreach (var item in nodes)

{

    Debug.WriteLine(item.Name);

}

 

--完--

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.