开发者

Validate cyclic organization unit

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜