第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

使用LINQ搜索樹

使用LINQ搜索樹

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

3 回答

?
慕娘9325324

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊

這需要遞歸是一個(gè)誤解。這將需要一個(gè)堆?;蜿?duì)列和最簡(jiǎn)單的方法是使用遞歸來實(shí)現(xiàn)它。為了完整起見,我將提供一個(gè)非遞歸答案。


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);

    }

}

例如,使用以下表達(dá)式來使用它:


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


查看完整回答
反對(duì) 回復(fù) 2019-11-22
?
慕桂英546537

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊

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


static class NodeExtensions

{

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

    {

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

    }

}

然后,可以像其他任何查詢一樣使用where或first或其他查詢?cè)摽擅杜e的對(duì)象。


查看完整回答
反對(duì) 回復(fù) 2019-11-22
?
慕的地10843

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊

用Linq搜索對(duì)象樹


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;

        }


    }

}


查看完整回答
反對(duì) 回復(fù) 2019-11-22
  • 3 回答
  • 0 關(guān)注
  • 446 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)