How to search Hierarchical Data with Linq

前端 未结 8 664
心在旅途
心在旅途 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 have tried two of the suggested codes and made the code a bit more clear:

        public static IEnumerable Flatten1(this T source, Func> selector)
        {
            return selector(source).SelectMany(c => Flatten1(c, selector)).Concat(new[] { source });
        }
    
        public static IEnumerable Flatten2(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))
                    stack.Push(child);
            }
        }
    

    Flatten2() seems to be a little bit faster but its a close run.

提交回复
热议问题