Guest User

Untitled

a guest
Jul 17th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. public class SomeObject
  2. {
  3. public String Name { get; set; }
  4. public List<SomeObject> SomeObjects { get; set; }
  5. }
  6.  
  7. public static void TraverseAndExecute<T>(this T composite, Func<T,IEnumerable<T>> selectChildren, Action<T> action)
  8. where T: class
  9. {
  10. action.Invoke(composite);
  11. composite.TraverseAndExecute(selectChildren, action, new List<T>{ composite });
  12. }
  13.  
  14. private static void TraverseAndExecute<T>(this T composite, Func<T,IEnumerable<T>> selectChildren, Action<T> action, IList<T> invokedComponents)
  15. where T: class
  16. {
  17. invokedComponents = invokedComponents ?? new List<T>();
  18. var components = selectChildren(composite) ?? new T[]{};
  19. foreach(var component in components){
  20. // To avoid an infinite loop in the case of circular references, ensure
  21. // that you don't loop over an object that has already been traversed
  22. if(!invokedComponents.Contains(component)){
  23. action.Invoke(component);
  24. invokedComponents.Add(component);
  25. component.TraverseAndExecute<T>(selectChildren, action, invokedComponents);
  26. }
  27. else{
  28. // the code to execute in the event of a circular reference
  29. // would go here
  30. }
  31. }
  32. }
  33.  
  34. public class Program{
  35. public static void Main(){
  36. var someObject = new SomeObject {
  37. Name = "Composite",
  38. SomeObjects = new List<SomeObject>{
  39. new SomeObject{ Name = "Leaf 1" },
  40. new SomeObject{
  41. Name = "Nested Composite",
  42. SomeObjects = new List<SomeObject>{ new SomeObject{Name = "Deep Leaf" }}
  43. }
  44. }
  45. };
  46. someObject.TraverseAndExecute(
  47. x => x.SomeObjects,
  48. x => { Console.WriteLine("Name: " + x.Name); }
  49. );
  50. }
  51. }
Add Comment
Please, Sign In to add comment