I have a domain object that I have no control over which itself contains a collection of this same type. This is a classical hierarichal representation like in a tree node hierarchy. I would like to be able to enumerate the whole hierarchy in a single call so I came up with this extension method:
public static class MyObjectExtensions
{
public static IEnumerable<MyObject> FindAllObjectsRecursive(this MyObject myObject)
{
var objects = new List<MyObject>();
objects.Add(myObject);
foreach (MyObject innerObject in myObject.Objects)
{
objects.AddRange(innerObject.FindAllObjectsRecursive());
}
return objects;
}
}
Unfortunately I am not really satisfied by this method because it would definitely cause issues in a large tree span scenario. So I was wondering if anyone would have a solution for that. I did think of using a parameter for the list but I was thinking there must be a better solution.
Here is how I intend to use this method:
var myObject = new MyObject();
var allObjects = myObject.FindAllObjectsRecursive();
And here is the domain object:
public class MyObject
{
public IEnumerable<MyObject> Objects { get; set; }
}