开发者

Traverse hierarchy object c#

开发者 https://www.devze.com 2023-03-16 00:20 出处:网络
If I have a Class like below. How do i traverse through it until i开发者_如何学Gots property SomeObjects.count = 0

If I have a Class like below. How do i traverse through it until i开发者_如何学Gots property SomeObjects.count = 0

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

Many Thanks


Here is a generic example of how you can traverse a composite object:

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
            }
        }
    }
}

Here is a sample usage:

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); }
       );
    }
}


This is a tree-like structure; there are many algorithms for traversing it, you can search for tree-traversal algorithms and you'll find many of them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号