If I have a hierarchical structure of departments and employees, like this:
public class TestEmployee
{
public Guid ID { get; set; }
public Guid TestDepartmemntID { get; set; }
public string name { get; set; }
public string email { get; set; }
}
public class TestDepartmemnt
{
public Guid ID { get; set; }
public Guid ParentTestDepartmentID { get; set; }
public string TestDepartmentName { get; set; }
public string? ManagerName { get; set; }
public string phoneNumber { get; set; }
}
Noting that ManagerName is nullable...
Is there a more elegant way to get employee's direct managername other than iterating up ancestors to find the closest department manager name?
If Widgets Inc has CEO Bob at the root, and Bob manages several departments, one of which is Logistics.
Logistics has several departments, one is Warehouse. Warehouse has a manager of Sharon.
The Warehouse has multiple departments, including shipping and receiving.
Rick works in shipping.
Rick's manager is Sharon.
I can easily determine which department Rick works in because I can get the TestDepartmentID.
However, when getting Rick out of the tree, do I have to get do something like: Get Ricks TestDepartmentID's closest ancestors where ManagerName is not null or empty?
Is there a more elegant way to do this than a recursive loop?
Linq operates on IEnumerables, so the first step would be to create one. For example by using an iterator block. You can then use .First()
or any other linq methods to return the first non-null manager, or any other query you want.
public Dictionary<Guid, TestDepartmemnt> departments = new Dictionary<Guid, TestDepartmemnt>();
public IEnumerable<TestDepartmemnt> GetParents(Guid departmentId)
{
while(departments.TryGetValue(departmentId, out var department))
{
yield return department;
departmentId = department.ParentTestDepartmentID;
}
}
This assumes you have the departments in a dictionary. This can be replaced with whatever method you use to link ids to departments.