How to use LINQ to select all descendants of a composite object

后端 未结 4 1768
终归单人心
终归单人心 2020-12-16 06:34

How can I make ComponentTraversal.GetDescendants() better using LINQ?

Question

public static class ComponentTraversal
{
    public sta         


        
4条回答
  •  执笔经年
    2020-12-16 07:06

    This is a good example for when you might want to implement an iterator. This has the advantage of lazy evaluation in a slightly more readable syntax. Also, if you need to add additional custom logic then this form is more extensible

     public static IEnumerable GetDescendants(this Composite composite)
        {
            foreach(var child in composite.Children)
            {
                yield return child;
                if(!(child is Composite))
                   continue;
    
                foreach (var subChild in ((Composite)child).GetDescendants())
                   yield return subChild;
            }
        }
    

提交回复
热议问题