このクラスから作成されたツリーがあります。
class Node
{
    public string Key { get; }
    public List<Node> Children { get; }
}
すべての子供とそのすべての子供を検索して、条件に一致するものを取得したいと思います。
node.Key == SomeSpecialKey
どうすれば実装できますか?
このクラスから作成されたツリーがあります。
class Node
{
    public string Key { get; }
    public List<Node> Children { get; }
}
すべての子供とそのすべての子供を検索して、条件に一致するものを取得したいと思います。
node.Key == SomeSpecialKey
どうすれば実装できますか?
回答:
これには再帰が必要であるというのは誤解です。それはなりますスタックやキューを必要とし、最も簡単な方法は、再帰を使用して、それを実装することです。完全を期すために、非再帰的な回答を提供します。
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)
    StackOverflowException。
                    Queue<Node>(対応する変更はEnqueue/DequeueからPush/になりますPop)。
                    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;
        }
    }
}
    headとchildrenFunc、メソッドを2つの部分に分割して、パラメーターチェックがトラバーサル時間に延期されないようにする必要があります。
                    Linqのような構文を維持したい場合は、メソッドを使用してすべての子孫(子+子の子など)を取得できます。
static class NodeExtensions
{
    public static IEnumerable<Node> Descendants(this Node node)
    {
        return node.Children.Concat(node.Children.SelectMany(n => n.Descendants()));
    }
}
この列挙型は、他の場所と同じように、where、first、または何でもクエリできます。
この拡張メソッドを試して、ツリーノードを列挙できます。
static IEnumerable<Node> GetTreeNodes(this Node rootNode)
{
    yield return rootNode;
    foreach (var childNode in rootNode.Children)
    {
        foreach (var child in childNode.GetTreeNodes())
            yield return child;
    }
}
次に、それをWhere()句とともに使用します。
var matchingNodes = rootNode.GetTreeNodes().Where(x => x.Key == SomeSpecialKey);
    たぶんあなたはただ必要です
node.Children.Where(child => child.Key == SomeSpecialKey)
または、1レベル深く検索する必要がある場合は、
node.Children.SelectMany(
        child => child.Children.Where(child => child.Key == SomeSpecialKey))
すべてのレベルで検索する必要がある場合は、次のようにしてください。
IEnumerable<Node> FlattenAndFilter(Node source)
{
    List<Node> l = new List();
    if (source.Key == SomeSpecialKey)
        l.Add(source);
    return
        l.Concat(source.Children.SelectMany(child => FlattenAndFilter(child)));
}
    public class Node
    {
        string key;
        List<Node> children;
        public Node(string key)
        {
            this.key = key;
            children = new List<Node>();
        }
        public string Key { get { return key; } }
        public List<Node> Children { get { return children; } }
        public Node Find(Func<Node, bool> myFunc)
        {
            foreach (Node node in Children)
            {
                if (myFunc(node))
                {
                    return node;
                }
                else 
                {
                    Node test = node.Find(myFunc);
                    if (test != null)
                        return test;
                }
            }
            return null;
        }
    }
そして、次のように検索できます。
    Node root = new Node("root");
    Node child1 = new Node("child1");
    Node child2 = new Node("child2");
    Node child3 = new Node("child3");
    Node child4 = new Node("child4");
    Node child5 = new Node("child5");
    Node child6 = new Node("child6");
    root.Children.Add(child1);
    root.Children.Add(child2);
    child1.Children.Add(child3);
    child2.Children.Add(child4);
    child4.Children.Add(child5);
    child5.Children.Add(child6);
    Node test = root.Find(p => p.Key == "child6");
    IEnumerable<T>拡張メソッドを使用しないのはなぜですか
public static IEnumerable<TResult> SelectHierarchy<TResult>(this IEnumerable<TResult> source, Func<TResult, IEnumerable<TResult>> collectionSelector, Func<TResult, bool> predicate)
{
    if (source == null)
    {
        yield break;
    }
    foreach (var item in source)
    {
        if (predicate(item))
        {
            yield return item;
        }
        var childResults = SelectHierarchy(collectionSelector(item), collectionSelector, predicate);
        foreach (var childItem in childResults)
        {
            yield return childItem;
        }
    }
}
次に、これを実行します
var result = nodes.Children.SelectHierarchy(n => n.Children, n => n.Key.IndexOf(searchString) != -1);
    しばらく前に、Linqを使用してツリーのような構造をクエリする方法を説明するcodeprojectの記事を書きました。
http://www.codeproject.com/KB/linq/LinqToTree.aspx
これにより、子孫、子、祖先などを検索できるlinq-to-XMLスタイルのAPIが提供されます。
おそらくあなたの現在の問題にはやり過ぎですが、他の人にとっては興味深いかもしれません。
私は任意IEnumerable<T>をフラット化できる一般的な拡張メソッドを持っており、そのフラット化されたコレクションから、必要なノードを取得できます。
public static IEnumerable<T> FlattenHierarchy<T>(this T node, Func<T, IEnumerable<T>> getChildEnumerator)
{
    yield return node;
    if (getChildEnumerator(node) != null)
    {
        foreach (var child in getChildEnumerator(node))
        {
            foreach (var childOrDescendant in child.FlattenHierarchy(getChildEnumerator))
            {
                yield return childOrDescendant;
            }
        }
    }
}
このようにこれを使用してください:
var q = from node in myTree.FlattenHierarchy(x => x.Children)
        where node.Key == "MyKey"
        select node;
var theNode = q.SingleOrDefault();
    ツリーアイテムを列挙するために次の実装を使用します
    public static IEnumerable<Node> DepthFirstUnfold(this Node root) =>
        ObjectAsEnumerable(root).Concat(root.Children.SelectMany(DepthFirstUnfold));
    public static IEnumerable<Node> BreadthFirstUnfold(this Node root) {
        var queue = new Queue<IEnumerable<Node>>();
        queue.Enqueue(ObjectAsEnumerable(root));
        while (queue.Count != 0)
            foreach (var node in queue.Dequeue()) {
                yield return node;
                queue.Enqueue(node.Children);
            }
    }
    private static IEnumerable<T> ObjectAsEnumerable<T>(T obj) {
        yield return obj;
    }
上記の実装のBreadthFirstUnfoldは、ノードキューの代わりにノードシーケンスのキューを使用します。これは、従来のBFSアルゴリズムの方法ではありません。
そして、楽しみのために(ほぼ10年後)、ジェネリックを使用しているが、@ vidstigeによって受け入れられた回答に基づいて、スタックとWhileループを使用した回答。
public static class TypeExtentions
{
    public static IEnumerable<T> Descendants<T>(this T root, Func<T, IEnumerable<T>> selector)
    {
        var nodes = new Stack<T>(new[] { root });
        while (nodes.Any())
        {
            T node = nodes.Pop();
            yield return node;
            foreach (var n in selector(node)) nodes.Push(n);
        }
    }
    public static IEnumerable<T> Descendants<T>(this IEnumerable<T> encounter, Func<T, IEnumerable<T>> selector)
    {
        var nodes = new Stack<T>(encounter);
        while (nodes.Any())
        {
            T node = nodes.Pop();
            yield return node;
            if (selector(node) != null)
                foreach (var n in selector(node))
                    nodes.Push(n);
        }
    }
}
コレクションが与えられると、このように使用できます
        var myNode = ListNodes.Descendants(x => x.Children).Where(x => x.Key == SomeKey);
またはルートオブジェクトを使用
        var myNode = root.Descendants(x => x.Children).Where(x => x.Key == SomeKey);