我在递归求和计算中遇到了一点困难。
我有一个学生容器类,所有学生都在对象类学生中(学生有他们的名字、姓氏......以及他们的成绩)。我将学生的成绩保存在 arraylist 中,并且我想要容器类中的递归方法,它可以计算 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。