Custom object referring to itself, how to stop it looping forever?
I have a custom object of School, which is part of a family of schools. So when I return a school, I can return the schools it is linked to in its family.
However, when I do this it manages to loop forever, how can I stop it. Like only going 1 level deep and not becoming recursive?
public class 开发者_运维问答School
{
public long BaseId { get; set; }
public string BaseName { get; set; }
public string SchoolFamily { get; set; }
public List<School> LinkedSchools
{
get
{
var schoolRepository = new SchoolRepository();
return schoolRepository.GetAllSchoolsLinkedByFamily(SchoolFamily).ToList();
}
set { ; }
}
}
Add a Boolean member variable to act as a flag, default cleared. First thing to do in the get function is check that flag. If it is set, return an empty list. Otherwise set the flag, create the list, and clear the flag, then return the list.
You can pass the current instance of your School (this) into the GetAllSchoolsLinkedByFamily
and when that reaches the instance you can stop.
Change the LinkedSchools
property to be a method that accepts an optional integer parameter of nestLevel
. Something like this:
public List<School> GetLinkedSchools(int nestLevel)
{
// Get schools logic here...
}
Then change your code so that each level of recursion increments a counter and returns once the counter is equal to nestLevel
.
I would recommend first adding the current school to the return Collection and passing that Collection through each recursive iteration. Then, inside the iteration method, only add / perform a deeper iteration for the schools that are not already in the list. In this way you get all of the related schools but no endless recursion.
Edit: Mark Jones Graph Traversal (marking visited nodes) suggestion below is actually cheaper if you don't mind adorning your class.
精彩评论