【发布时间】:2026-02-05 22:30:02
【问题描述】:
所以我的 ArrayList 看起来像这样:
using System.Collections;
[...]
//in main:
Student s01 = new Student
{
name = "John",
surname = "Doa"
};
Student s02 = new Student
{
name = "John",
surname = "Doe"
};
Student s03 = new Student
{
name = "John",
surname = "Doi"
};
Student s04 = new Student
{
name = "John",
surname = "Doo"
};
Student s05 = new Student
{
name = "John",
surname = "Dou"
};
ArrayList studentsList = new ArrayList();
studentsList.Add(s03);
studentsList.Add(s04);
studentsList.Add(s05);
studentsList.Add(s01);
studentsList.Add(s02);
学生.cs:
class Student : IPerson
{
public string name;
public string surname;
public void Describe()
{
Console.WriteLine("{0} {1}", name, surname);
}
我想按surname 对studentsList 中的对象进行排序,并在foreach 循环中写下姓名+姓氏。我知道studentsList.Sort(); 不起作用,因为它不知道应该以什么方式将每个对象与其他对象进行比较-
这就是我卡住的地方,因为我真的不知道如何编写使用 arrayList 中对象字段值的新比较器。我什至不知道如何开始。
我必须使用 ArrayList,但我不必直接对其进行排序(我猜我可以使用强制转换) - 最后它必须看起来像:
1. John Doa
2. John Doe
3. John Doi
4. John Doo
5. John Dou
Sort()studentsList 会很棒,因为我可以这样做:
int i = 0;
foreach (Student s in studentsList)
{
i++;
Console.Write("{0}. ", i);
s.Describe();
}
【问题讨论】:
-
为什么必须使用 ArrayList?这是作业吗?
-
那种。这是一项测试任务,我为此而学习。
-
您还需要添加
using System.Linq才能使用它。 -
您好像错过了
OfType<Student>()电话。但请注意,ArrayList现在很少在实际代码中使用 - 自 2005 年以来它已经基本过时了。