如何对数组元素进行排序

时间:2019-04-14 12:05:42

标签: c#

我正在尝试使用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

1 个答案:

答案 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);
}
相关问题