I've got a class that looks like this:
public class SourceObject
{
public string Id { get; set; }
public List<SourceObject> Children { get; set; }
public SourceObject()
{
Children = new List<SourceObject>();
}
}
As you can see, it has a property that contains a list of further instances of this same class. The data I'm dealing with for this class means that the number of children is unknown until runtime and the overall "depth" of the resulting object graph is also unknown.
I need to create a "mapping" from the object graph of SourceObject
to a similarly shaped graph of DestinationObject
's (similar to how AutoMapper might map from one object to another).
I've got a method that will map from my Source graph to my Destination graph, however, this method uses recursion:
// Recursive way of mapping each Source object to Destination
public static DestinationObject MapSourceToDestination(SourceObject source)
{
var result = new DestinationObject();
result.Id = source.Id;
result.Children = source.Children.Select(MapSourceToDestination).ToList();
return result;
}
This works fine when the size of the source object graph isn't too large or deep, however, when the source object graph is very large, this method will throw a StackOverflow exception.
I have managed to create an alternative version of this function that removes the recursion and replaces it with a Queue/Stack using a technique similar to that described in this answer) however, I've noticed that the Queue/Stack can also grow very large and I'm not sure that my implementation is the most efficient.
Is it possible to convert the recursive function to one that purely uses iteration over the source object graph (i.e. removing recursion and ideally, the use of a Queue/Stack)?