A modified Employee
class that exposes two methods to query an employee subordinates.
Uses recursion in slightly different way.
The lists are ordered by FirstName
then LastName
.
One method returns only the direct subordinates:
public string GetDirectSubordinates()
The other one returns all subordinates in a hierarchical representation:
public string GetAllSubordinates()
public class Employee
{
StringBuilder sb = null;
public Employee(): this("", "") { }
public Employee(string Firstname, string Lastname)
{
this.sb = new StringBuilder();
this.Subordinates = new List<Employee>();
this.FirstName = Firstname;
this.LastName = Lastname;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Employee> Subordinates { get; set; }
public string GetDirectSubordinates()
{
if (this.Subordinates == null) return string.Empty;
return string.Join(Environment.NewLine, Subordinates
.OrderBy(s => s.LastName).ThenBy(s => s.FirstName)
.Select(se => '\t' + se.ToString()));
}
public string GetAllSubordinates()
{
sb.Append(this.ToString() + " Subordinates:" + Environment.NewLine);
return GetSubordinateList(1);
}
private string GetSubordinateList(int SubLevel)
{
foreach (Employee Subordinate in this.Subordinates.OrderBy(sb => sb.FirstName).ThenBy(sb => sb.LastName))
{
sb.Append(new string('\t', SubLevel) + ((SubLevel == 1) ? "• " : "– ") + Subordinate.ToString() + Environment.NewLine);
if (Subordinate.Subordinates != null && Subordinate.Subordinates.Count > 0)
{
sb.Append(Subordinate.GetSubordinateList(SubLevel + 1) + Environment.NewLine);
}
}
string result = sb.ToString();
sb.Clear();
return result;
}
public override string ToString() => $"{this.FirstName} {this.LastName}";
}
Assign some Employees values and add some of them as subordinates and sub-subordinates:
Employee Director = new Employee("John", "McDir");
Employee SubDirector1 = new Employee("Jane", "Doe");
Employee SubDirector2 = new Employee("Mary", "Fairchild");
Employee CoSub1 = new Employee("Ted", "Smith");
Employee CoSub2 = new Employee("Bob", "Jones");
Employee CoSub3 = new Employee("J. B.", "Fletcher");
Employee CoSub4 = new Employee("Larry", "VanLast");
Employee Rookie1 = new Employee("Mick", "Fresh");
Employee Rookie2 = new Employee("Hugh", "DeGreen");
Director.Subordinates.AddRange(new[] { SubDirector1, SubDirector2} );
SubDirector1.Subordinates.AddRange(new[] { CoSub1, CoSub2 });
SubDirector2.Subordinates.AddRange(new[] { CoSub3, CoSub4 });
CoSub3.Subordinates.Add(Rookie1);
CoSub4.Subordinates.Add(Rookie2);
string DirectSubordinates = Director.GetDirectSubordinates();
returns:
Jane Doe
Mary Fairchild
string AllSubordinates = Director.GetAllSubordinates();
returns:
(You need a Font that supports Unicode simbols to print the •)
John McDir Subordinates:
• Jane Doe
- Bob Jones
- Ted Smith
• Mary Fairchild
- J. B. Fletcher
- Mick Fresh
- Larry VanLast
- Hugh DeGreen