我正在尝试使用C#对某些数组元素(具有字符串和整数)进行排序。我目前正在尝试使用Array.Sort
方法。
Student[] students = new Student[] {
new Student("Jane", "Smith", "Bachelor of Engineering", 6),
new Student("John", "Smith", "Bachelor of Engineering", 7),
new Student("John", "Smith", "Bachelor of IT", 7),
new Student("John", "Smith", "Bachelor of IT", 6),
new Student("Jane", "Smith", "Bachelor of IT", 6),
new Student("John", "Bloggs", "Bachelor of IT", 6),
new Student("John", "Bloggs", "Bachelor of Engineering", 6),
new Student("John", "Bloggs", "Bachelor of IT", 7),
new Student("John", "Smith", "Bachelor of Engineering", 6),
new Student("Jane", "Smith", "Bachelor of Engineering", 7),
new Student("Jane", "Bloggs", "Bachelor of IT", 6),
new Student("Jane", "Bloggs", "Bachelor of Engineering", 6),
new Student("Jane", "Bloggs", "Bachelor of Engineering", 7),
new Student("Jane", "Smith", "Bachelor of IT", 7),
new Student("John", "Bloggs", "Bachelor of Engineering", 7),
new Student("Jane", "Bloggs", "Bachelor of IT", 7),
};
Array.Sort(students);
foreach (Student student in students) {
Console.WriteLine("{0}", student);
}
我需要:
以便它返回:
Smith, Jane (Bachelor of Engineering) Grade: 6
Smith, John (Bachelor of Engineering) Grade: 6
Smith, Jane (Bachelor of Engineering) Grade: 7
Smith, John (Bachelor of Engineering) Grade: 7
Smith, Jane (Bachelor of IT) Grade: 6
Smith, John (Bachelor of IT) Grade: 6
Smith, Jane (Bachelor of IT) Grade: 7
Smith, John (Bachelor of IT) Grade: 7
Bloggs, Jane (Bachelor of Engineering) Grade: 6
Bloggs, John (Bachelor of Engineering) Grade: 6
Bloggs, Jane (Bachelor of Engineering) Grade: 7
Bloggs, John (Bachelor of Engineering) Grade: 7
Bloggs, Jane (Bachelor of IT) Grade: 6
Bloggs, John (Bachelor of IT) Grade: 6
Bloggs, Jane (Bachelor of IT) Grade: 7
Bloggs, John (Bachelor of IT) Grade: 7
答案 0 :(得分:0)
假设您的对象看起来像:
public class Student
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string Degree { get; set; }
public int Grade { get; set; }
}
您可以使用Linq查询对其进行排序:
var sortedStudents = students
.OrderByDescending(s => s.LastName)
.ThenBy(s => s.Degree)
.ThenBy(s => s.Grade)
.ThenBy(s => s.FirstName);
foreach (var student in sortedStudents)
{
Console.WriteLine("{0}", student);
}