Ok. Caveat ... this is not necessarily the "best" solution.
First - here is my interpretation of your Area class - Note I have included the constructor suggested by @OriginalGriff
public class Area
{
public Area(int id, string description, int parentId)
{
Id = id;
Description = description;
ParentId = parentId;
}
public int Id { get; set; }
public string Description { get; set; }
public int ParentId { get; set; }
} This means I can do the data set up as follows
var areas = new List<Area>
{
new Area(1, "Continent", -1),
new Area(2, "Country", 1),
new Area(3, "Province", 2),
new Area(4, "City1", 3),
new Area(5, "Suburb1", 6),
new Area(6, "City2", 3),
new Area(7, "Suburb2", 6),
new Area(8, "Suburb3", 6),
new Area(9, "Suburb4", 4),
new Area(10, "House1", 7),
new Area(11, "House3", 9),
new Area(12, "House4", 8),
new Area(13, "House5", 8),
new Area(14, "House6", 7)
}; Now I need a recursive function. I chose to do this as an Extension of the List class but you could just have it as a private method within your program
static class Extensions
{
public static void PrintChildren(this List<Area> areas, Area a, int level)
{
Console.WriteLine("{0}{1}", new String('-', level), a.Description);
var childrenIds = areas.Where(x => x.ParentId.Equals(a.Id)).ToList();
if (childrenIds.Count <= 0) return;
foreach (var c in childrenIds)
PrintChildren(areas, c, level + 1);
}
}
Things to note - I'm passing the "level of recursion" down the stack to make it easier to work out how many '-' characters to insert. And the function "calls itself" if the node has any children at all.
To start off the process just use
areas.PrintChildren(areas[0], 0);
Console.ReadLine(); in your Main method.
It really is worth following this through in your IDE debugger - put a break point on
Console.WriteLine("{0}{1}", new String('-', level), a.Description); and look at your "Locals" window in the IDE. Try to follow what is actually happening. You can also right-click on the function name and "Show Call Stack on Code Map" to see what is happening.
This looks like homework, so remember your tutor may also spot this answer - make sure you do the debug bit so you understand what is going on.
|