开发者

Validate cyclic organization unit

开发者 https://www.devze.com 2022-12-24 04:44 出处:网络
I have a object Organization Unit and I have a self reference to it in the same object public class OrganizationUnit: IOrganizationUnit{

I have a object Organization Unit and I have a self reference to it in the same object

public class OrganizationUnit: IOrganizationUnit  {

        private string fName;

        public string Name {
            get { return fName; }
            set { SetPropertyValue("Name", ref fName, (string) value); }
        }



        private OrganizationUnit fManagedBy;

        public IOrganizationUnit ManagedBy {
            get { return fManagedBy; }
            set {

                SetPropertyValue("ManagedBy", ref fManagedBy, (OrganizationUnit)value);
            }
        }


}

I need a method that will throw an exception if it finds a child organization unit in the third level is referencing a parent Organization unit, or to say cyclic parent organization.


Walk the graph and keep a history of visited nodes. If you visit a node again, you've detected a cycle:

void CheckCycles(IOrganizationUnit unit)
{
    var visited = new HashSet<IOrganizationUnit>();

    for (var current = unit; current != null; current = current.ManagedBy)
    {
        if (!visited.Add(current))
        {
            throw new Exception(); // cycle detected
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号