遍历层次结构对象c#

本文关键字:对象 层次结构 遍历 | 更新日期: 2023-09-27 18:00:28

如果我有一个类似下面的类。我如何遍历它,直到它的属性SomeObjects.count=0

public class SomeObject
{
  public String Name { get; set; }
  public List<SomeObject> SomeObjects { get; set; }
}

非常感谢

遍历层次结构对象c#

以下是如何遍历复合对象的一般示例:

public static class TraversalHelper{
    public static void TraverseAndExecute<T>(this T composite, Func<T,IEnumerable<T>> selectChildren, Action<T> action)
        where T: class
    {
         action.Invoke(composite);
         composite.TraverseAndExecute(selectChildren, action, new List<T>{ composite });
    }
    private static void TraverseAndExecute<T>(this T composite, Func<T,IEnumerable<T>> selectChildren, Action<T> action, IList<T> invokedComponents)
        where T: class
    {
        invokedComponents = invokedComponents ?? new List<T>();
        var components = selectChildren(composite) ?? new T[]{};
        foreach(var component in components){
            // To avoid an infinite loop in the case of circular references, ensure 
            // that you don't loop over an object that has already been traversed
            if(!invokedComponents.Contains(component)){
                action.Invoke(component);
                invokedComponents.Add(component);
                component.TraverseAndExecute<T>(selectChildren, action, invokedComponents);
            }
            else{
                // the code to execute in the event of a circular reference
                // would go here
            }
        }
    }
}

以下是示例用法:

public class Program{
    public static void Main(){
   var someObject = new SomeObject { 
                        Name = "Composite",
                        SomeObjects = new List<SomeObject>{
                            new SomeObject{ Name = "Leaf 1" },
                            new SomeObject{ 
                                Name = "Nested Composite",
                                SomeObjects = new List<SomeObject>{ new SomeObject{Name = "Deep Leaf" }}
                            }
                        }
                    };
   someObject.TraverseAndExecute(      
                      x => x.SomeObjects, 
                      x => { Console.WriteLine("Name: " + x.Name); }
       );
    }
}

这是一个树状结构;遍历它有很多算法,你可以搜索树遍历算法,你会发现很多。