如何以递归方法从列表中返回字符串

时间:2018-08-19 18:56:39

标签: c#

我的问题就像Recursive reading of List。但是,我必须返回一个字符串而不是void。当另一个方法调用它时,它将返回格式化的字符串。

我一直坚持使用缩进格式设置字符串以及如何进行递归操作。

public class Name
{
    public string FirstName { get; set; }
}

返回值应类似于下面的列表。

  • 简·多伊
    • 泰德·史密斯
      • 鲍勃·琼斯
  • 玛丽·费尔柴尔德(Mary Fairchild)
    • J。弗莱彻

5 个答案:

答案 0 :(得分:0)

我用此方法看到的第一个问题是它没有退出路径,每个递归方法都需要有一个。该路径定义了堆栈最后一项的预期输出。如果您在期望的输出中扩展更多内容,则应该直接编写路径

答案 1 :(得分:0)

    public void PrintEmployeeHierarchy(List<Employee> nestedEmployees, ref string result)
    {
        foreach (Employee employee in nestedEmployees)
        {
            if (employee.Subordinates != null && employee.Subordinates.Count > 0)
            {
                PrintEmployeeHierarchy(employee.Subordinates, ref result);
            }
            result += string.Format("{0} {1} {2}", employee.FirstName, employee.LastName, "\t");
        }
    }

呼叫方式:

  string data = "";
  PrintEmployeeHierarchy(empList, ref data);

答案 2 :(得分:0)

由于这可能是一个无限深的结构,因此您应该选择使用迭代方法而不是递归方法。结果,这将使您避免遇到堆栈溢出异常。您应该为此使用堆栈数据结构。

为此编写解决方案在迭代时会有些繁琐。但是,如果这是针对企业解决方案的,您需要能够在生产环境中使用不确定的深度,则递归通常是一种不好的做法。

如果这是个人工作,而且不会太深入,那么使用Valeh的解决方案应该可以正常工作。

答案 3 :(得分:0)

您可以使用`ref-parameter'来使相同的结果字符串可在所有嵌套中访问。

我会在ToString中覆盖Employee,以使打印更容易:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Employee> Subordinates { get; set; }

    public override string ToString()
    {
        return $"{FirstName} {LastName}";
    }
}

使用此辅助方法

private static string Indent(int nestingLevel)
{
    return new string(' ', 4 * nestingLevel);
}

可以这样打印层次结构

public void GetEmployeeHierarchy(List<Employee> employees, int level, ref string result)
{
    foreach (Employee emp in employees) {
        result += $"{Indent(level)}- {emp}\r\n";
        GetEmployeeHierarchy(emp.Subordinates, level + 1, ref result);
    }
}

请注意,我添加了一个level参数,该参数用于确定缩进。我还重命名了该方法,因为它不显示任何内容。

使用适当的列表设置此代码

string result = null;
GetEmployeeHierarchy(emps, 0, ref result);
Console.WriteLine(result);
Console.ReadKey();

在我的控制台上打印此内容(也尝试了项目符号,但不在控制台上打印):

- Jane Doe
    - Ted Smith
        - Bob Jones
- Mary Fairchild
    - J.B. Fletcher

答案 4 :(得分:0)

经过修改的 JS: NavigationStart(id: 3, url: '/home/collections/add/documents/addDoc') JS: RoutesRecognized(id: 3, url: '/home/collections/add/documents/addDoc', urlAfterRedirects: '/home/collections/add/documents/addDoc', state: Route(url:'', path:'') { Route(url:'home', path:'home') { Route(url:'collections/add', path:'collections/:collection') { Route(url:'documents/addDoc', path:'documents/addDoc') } } } ) JS: GuardsCheckStart(id: 3, url: '/home/collections/add/documents/addDoc', urlAfterRedirects: '/home/collections/add/documents/addDoc', state: Route(url:'', path:'') { Route(url:'home', path:'home') { Route(url:'collections/add', path:'collections/:collection') { Route(url:'documents/addDoc', path:'documents/addDoc') } } } ) JS: ChildActivationStart(path: 'collections/:collection') JS: ActivationStart(path: 'documents/addDoc') JS: GuardsCheckEnd(id: 3, url: '/home/collections/add/documents/addDoc', urlAfterRedirects: '/home/collections/add/documents/addDoc', state: Route(url:'', path:'') { Route(url:'home', path:'home') { Route(url:'collections/add', path:'collections/:collection') { Route(url:'documents/addDoc', path:'documents/addDoc') } } } , shouldActivate: true) JS: ResolveStart(id: 3, url: '/home/collections/add/documents/addDoc', urlAfterRedirects: '/home/collections/add/documents/addDoc', state: Route(url:'', path:'') { Route(url:'home', path:'home') { Route(url:'collections/add', path:'collections/:collection') { Route(url:'documents/addDoc', path:'documents/addDoc') } } } ) JS: ResolveEnd(id: 3, url: '/home/collections/add/documents/addDoc', urlAfterRedirects: '/home/collections/add/documents/addDoc', state: Route(url:'', path:'') { Route(url:'home', path:'home') { Route(url:'collections/add', path:'collections/:collection') { Route(url:'documents/addDoc', path:'documents/addDoc') } } } ) JS: ActivationEnd(path: 'documents/addDoc') JS: ChildActivationEnd(path: 'collections/:collection') JS: ActivationEnd(path: 'collections/:collection') JS: ChildActivationEnd(path: 'home') JS: ActivationEnd(path: 'home') JS: ChildActivationEnd(path: '') JS: NavigationEnd(id: 3, url: '/home/collections/add/documents/addDoc', urlAfterRedirects: '/home/collections/add/documents/addDoc') JS: Scroll(anchor: 'null', position: 'null') 类,提供了两种查询员工下属的方法。
使用递归的方式略有不同。
列表按Employee然后FirstName排序。

一种方法仅返回直接下属:
LastName

另一个以分级表示形式返回所有下属:
public string GetDirectSubordinates()

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}";
}

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();

Jane Doe Mary Fairchild 返回:
(您需要一种支持Unicode符号的字体才能打印•)

string AllSubordinates = Director.GetAllSubordinates();