How to search Hierarchical Data with Linq

前端 未结 8 663
心在旅途
心在旅途 2020-12-03 11:43

I need to search a tree for data that could be anywhere in the tree. How can this be done with linq?

class Program
{
    static void Main(string[] args) {

         


        
8条回答
  •  情深已故
    2020-12-03 12:21

    I like Kenneth Bo Christensen's answer using stack, it works great, it is easy to read and it is fast (and doesn't use recursion). The only unpleasant thing is that it reverses the order of child items (because stack is FIFO). If sort order doesn't matter to you then it's ok. If it does, sorting can be achieved easily using selector(current).Reverse() in the foreach loop (the rest of the code is the same as in Kenneth's original post)...

    public static IEnumerable Flatten(this T source, Func> selector)
    {            
        var stack = new Stack();
        stack.Push(source);
        while (stack.Count > 0)
        {
            var current = stack.Pop();
            yield return current;
            foreach (var child in selector(current).Reverse())
                stack.Push(child);
        }
    }
    

提交回复
热议问题