How to search Hierarchical Data with Linq

前端 未结 8 686
心在旅途
心在旅途 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:15

    Another solution without recursion...

    var result = FamilyToEnumerable(familyRoot)
                    .Where(f => f.Name == "FamilyD");
    
    
    IEnumerable FamilyToEnumerable(Family f)
    {
        Stack stack = new Stack();
        stack.Push(f);
        while (stack.Count > 0)
        {
            var family =  stack.Pop();
            yield return family;
            foreach (var child in family.Children)
                stack.Push(child);
        }
    }
    

提交回复
热议问题