亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用LINQ搜索樹

使用LINQ搜索樹

哈士奇WWW 2019-11-22 15:47:28
我有一個從該類創建的樹。class Node{    public string Key { get; }    public List<Node> Children { get; }}我想搜索所有孩子及其所有孩子,以找到符合條件的孩子:node.Key == SomeSpecialKey我該如何實施?
查看完整描述

3 回答

?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

這需要遞歸是一個誤解。這將需要一個堆?;蜿犃泻妥詈唵蔚姆椒ㄊ鞘褂眠f歸來實現它。為了完整起見,我將提供一個非遞歸答案。


static IEnumerable<Node> Descendants(this Node root)

{

    var nodes = new Stack<Node>(new[] {root});

    while (nodes.Any())

    {

        Node node = nodes.Pop();

        yield return node;

        foreach (var n in node.Children) nodes.Push(n);

    }

}

例如,使用以下表達式來使用它:


root.Descendants().Where(node => node.Key == SomeSpecialKey)


查看完整回答
反對 回復 2019-11-22
?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

如果您想要維護類似于Linq的語法,則可以使用一種方法來獲取所有后代(子代+孩子的子代等)。


static class NodeExtensions

{

    public static IEnumerable<Node> Descendants(this Node node)

    {

        return node.Children.Concat(node.Children.SelectMany(n => n.Descendants()));

    }

}

然后,可以像其他任何查詢一樣使用where或first或其他查詢該可枚舉的對象。


查看完整回答
反對 回復 2019-11-22
?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

用Linq搜索對象樹


public static class TreeToEnumerableEx

{

    public static IEnumerable<T> AsDepthFirstEnumerable<T>(this T head, Func<T, IEnumerable<T>> childrenFunc)

    {

        yield return head;


        foreach (var node in childrenFunc(head))

        {

            foreach (var child in AsDepthFirstEnumerable(node, childrenFunc))

            {

                yield return child;

            }

        }


    }


    public static IEnumerable<T> AsBreadthFirstEnumerable<T>(this T head, Func<T, IEnumerable<T>> childrenFunc)

    {

        yield return head;


        var last = head;

        foreach (var node in AsBreadthFirstEnumerable(head, childrenFunc))

        {

            foreach (var child in childrenFunc(node))

            {

                yield return child;

                last = child;

            }

            if (last.Equals(node)) yield break;

        }


    }

}


查看完整回答
反對 回復 2019-11-22
  • 3 回答
  • 0 關注
  • 449 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號