数组列表的递归方法



晚上好,伙计们,我在递归和计算中有点卡住了。

我有一个学生的容器类,所有学生都在对象类学生中(学生有他的名字,姓氏...和他的成绩(。我正在将学生的成绩保存在数组列表中,我想要容器类中的递归方法,该方法可以在 ArrayList 中计算这些成绩.我知道如何以迭代方式做到这一点,但不确定它的递归版本。

学生班

class Student
{
    public ArrayList grades = new ArrayList();
    public Student(ArrayList grades)
    {
        this.grades = grades;
    }
}

学生班(容器(

class Students
{
    private Student[] studentOb{ get; set; }
    public int containerNumber{ get; private set; }
    public Students(int size)
    {
        studentOb = new Student[size];
    }
    public void AddElement(Student info)
    {
        studentOb[containerNumber++] = info;
    }
    public Student TakeElement(int index)
    {
        return studentOb[index];
    }
    //this is where I am trying to build that Sum method, and yeah my code is just nonsense
    public int Sum(ArrayList collection)
    {
        int ret = collection.Count;
        foreach (ArrayList newList in collection)
        {
            ret += Sum(newList)
        }
    }
}

您可以在没有递归的情况下做到这一点(这不是这里的最佳解决方案(。使用 LINQ 和 SelectMany,可以将 Sum 方法编写为:

public int Sum()
{
    return studentOb.SelectMany(x => x.grades.Cast<int>()).Sum();
}

还可以改进代码并将 ArrayList 替换为类型化集合。

最新更新