Sorry for the long post. I had this coding problem for an interview but couldnt figure out. Would really appreciate if someone could please help. Will prepare me better next time. There are two classes
class Emp
{
public string Name { get; set; }
public string Manager { get; set; }
}
class Roo
{
public string Name { get; set; }
public List<Roo> Children { get; set; }
}
Input data is a list of employee objects with name and their manager. Since RH has empty manager, it will be the root of top down output.
var empList = new List<Emp>();
empList.Add(new Emp { Name = "TD", Manager = "AV" });
empList.Add(new Emp { Name = "DL", Manager = "AV" });
empList.Add(new Emp { Name = "AV", Manager = "JS" });
empList.Add(new Emp { Name = "JS", Manager = "RH" });
empList.Add(new Emp { Name = "KM", Manager = "DD" });
empList.Add(new Emp { Name = "DD", Manager = "RH" });
empList.Add(new Emp { Name = "RH", Manager = "" });
I need to convert this list into an object of type Roo. If an employee has a manager, they become the children of the manager. Output json looks like this
My attempt is as follows but something is not right in the recursion function. Can someone please help.
var leader = empList.Where(x => x.Manager == string.Empty).FirstOrDefault();
var roo = new Roo();
var children = new List<Roo>();
roo.Name = leader.Name;
GetChildren(empList, leader.Name, ref children);
// Convert roo to Json
void GetChildren(List<Emp> empList, string name, ref List<Roo> children)
{
var list = empList.Where(x => x.Manager == name).ToList();
if (list.Any())
{
var roo = new Roo();
foreach(var l in list)
{
var newlist = empList.Where(x => x.Manager == l.Name).ToList();
if (newlist.Any())
GetChildren(newlist, l.Name, ref children);
else
{
roo = new Roo { Name = l.Name, Children = null };
children.Add(roo);
}
}
}
}