所以我的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);
Student.cs:
class Student : IPerson
{
public string name;
public string surname;
public void Describe()
{
Console.WriteLine("{0} {1}", name, surname);
}
我希望studentsList
按surname
排序我的对象,并在foreach
循环中记下姓名+姓氏。我知道studentsList.Sort();
无法工作,因为它不知道应该以何种方式将每个对象与其他对象进行比较 -
以及那个我被困的地方,因为我真的不知道如何编写使用arrayList中对象字段值的新比较器。 I甚至不知道如何开始。
我必须使用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();
}
答案 0 :(得分:1)
您还可以在Student中定义compareTo方法,以便能够使用studentList.Sort()。 学生班还应该扩展:IComparable
public int CompareTo(object obj)
{
if (obj == null) return 1;
Student other = obj as Student;
if (other != null)
{
// Compare last names first, then by firstName
int value = this.lastName.CompareTo(other.lastName);
if (value == 0)
value = this.firstName.CompareTo(other.firstName);
return value;
}
else
throw new ArgumentException("Object is not a Student");
}
答案 1 :(得分:0)
您可以按照以下方式执行此操作
ArrayList studentsList = new ArrayList();
studentsList.Add(s03);
studentsList.Add(s04);
studentsList.Add(s05);
studentsList.Add(s01);
studentsList.Add(s02);
var studentsList2 = studentsList.Cast<Student>().OrderBy(r => r.surname).ToList();
int i = 0;
foreach (Student s in studentsList2)
{
i++;
Console.Write("{0}. ", i);
s.Describe();
}
答案 2 :(得分:0)
foreach (var student in studentsList.OfType<Student>().OrderBy(x => x.surname).ThenBy(x => x.name))
{
i++;
Console.Write("{0}. ", i);
student.Describe();
}
按预期工作(感谢@Will,https://stackoverflow.com/users/1228/will),我没有意识到linq表达式会那么容易。话虽如此,这只是学术上的例子,因为自2005年以来,ArrayList已经过时了(@JonSkeet)。